基本上我试图通过 AJAX 发表评论,然后将新评论加载到 HTML 中。我认为我的 AJAX 成功功能有问题。数据很好地添加到数据库中,但我仍然收到错误“抱歉,意外错误。请稍后再试。” 如在成功函数本身内部设置的那样。
JS:
function newComment(event) {
event.preventDefault();
//Get the data from all the fields
var comment = $('textarea');
var product_id = $('input[name=product_id]');
var form_data = {
comment : comment.val(),
product_id : product_id.val()
};
//Simple validation to make sure user entered something
if (comment.val()=='') {
alert('Comment cannot be blank!');
return false;
}
//show the loading sign
$('#loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "main/ajax_comment",
//GET method is used
type: "POST",
//pass the data
data: form_data,
//success
success: function (c) {
//check the status
if (c.status==1) {
$('Posted By: ' + c.username + '<br> Body: ' + c.body + '<br> Posted On: ' + c.date + '<hr>').appendTo('#new_comment');
$('#loading').hide();
$('#new_comment').slideDown();
//0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
}
PHP:
public function ajax_comment()
{
sleep(4);
$this->main_model->add_comment($this->session->userdata('user_id'), $this->input->post('product_id'), $this->input->post('comment'));
$i = $this->auth_model->get_data_id($this->session->userdata('user_id'), 'user');
$return = array(
'status' => '1',
'username' => $i->username,
'body' => $this->input->post('comment'),
'date' => time()
);
echo json_encode($return);
}
HTML:
<form action="<?php echo base_url()."main/comment"; ?>" method="post">
<input type="hidden" name="product_id" value="<?php echo $p->u_product_id; ?>">
<textarea name="new_comment"></textarea><br>
<input type="submit" name="submit_comment" id="submit_comment" value="Post">
<div id="loading" style="display: none;">
<img src="<?php echo base_url()."assets/img/load.gif"; ?>">
</div>
难道我做错了什么?