我正在我的网站上准备一个'管理员'笔记表。基本上,我想做两件事:
- 使用 AJAX 将新注释插入到数据库中的"注释"表中。
- 如果插入成功,请使用 AJAX 更新页面上显示的备注表。
-
$('#form_add_btn').click(function(){
var form_data = {
note: $('#note_text').val(),
type: $('#form_type_select').val(),
}
$.ajax({
url: "<?php echo base_url();?>admin/add_note",
type: 'POST',
data: form_data,
success: function(msg)
{
$('#note_msg').html(msg);
}
});
return false;
});
目前,控制器方法 add_note() 通过模型添加注释并返回 true 或 false,将其加载到视图中并返回。
public function add_note() {
$note = $this->input->post('note');
$type = $this->input->post('type');
$data['is_success'] = $this->model_admin->add_note($note, $type);
$this->load->view('admin/add_note', $data);
}
如果$data['is_success']为真,我想做另一个AJAX请求:
$.ajax({
url: "<?php echo base_url();?>admin/get_notes_table",
type: 'POST',
success: function(table)
{
$('#wrap').html(table);
}
});
我该如何完成这个?我尝试将第二个请求放在第一个请求内部和之后,但我仍然需要知道插入是否成功。
我刚刚开始在jQuery中学习CI和AJAX,非常感谢您的帮助。谢谢!
您只能在一次 ajax 调用中执行此操作,只需更改add_note控制器函数,它应该返回 JSON,而不是在视图中返回真/假。此 json 将包含成功或假以及新的注释列表。您可以在成功函数中解析此 JSON 以显示注释。
public function add_note() {
$note = $this->input->post('note');
$type = $this->input->post('type');
$data['is_success'] = $this->model_admin->add_note($note, $type);
if($data['is_success']){
//get the new notes from the db including the new one
$data['result'] = "success";
$data['motes'] = notes from DB
}else{
$data['result'] = "fail";
}
echo json_encode($data);exit;
}
它的好处是,您的一个ajax调用被保存,意味着用户exp会更好,因为他不必等待更多。