我正在使用 ajax 将数据保存在 cakephp 应用程序中。ajax 的工作范围是保存数据——当我单击提交按钮时,评论会保存到数据库中,甚至会自动出现在我的评论列表中。但是,无论我尝试什么,“成功”功能都不会发生任何事情。我无法收到警报,但也无法收到错误警报。
这是怎么回事?这是否与 cake 返回数据的方式有关?在我的控制器的添加功能中,保存部分有效。检查请求是否为 ajax 的部分似乎没有做任何事情。我尝试在其中放置重定向,但页面没有重定向。明确一点:我不希望页面被重定向;我想留在页面上。但是,由于成功后我无能为力,因此无法显示“已保存”消息或清除表单字段或其他任何内容。想法?
// my jquery script
$(document).ready(function () {
// Turn submit button into an ajax call
$('#save-comment input').click(function(){
saveComment();
});
// This function is called when the "save" button is clicked
function saveComment()
{
var formdata = $('#comment-form').serialize();
$.ajax({
type: "POST",
url: "/cakeblog/comments/add",
data: formdata,
success: function(result) {
alert("success");
},
error:function (){
alert('error');
}
});
}
});
// my controller
class CommentsController extends AppController {
public $name = 'Comments';
public function add() {
if (!empty($this->data)) {
if($this->Comment->save($this->data)){
if($this->request->is('ajax')){
// nothing I put here seems to do anything
$this->redirect(array('action'=>'index'));
} else {
$this->Session->setFlash('Message sent');
$this->redirect(array('action'=>'index'));
}
}
}
}
}