1

我正在使用 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'));
  }
    }
  }
}
}
4

2 回答 2

1

您尚未在控制器中返回 Http 响应。您需要返回Http Responsefunction add()为此,您需要echo在控制器中。

似乎检测 ajax 是错误的......在下面使用来检测 ajax。

$this->set('isAjax', $this->RequestHandler->isAjax());

还有一件事情。你在你的控制器中重定向。你不能在那个视图中重定向。您必须在成功调用 ajax 时执行此操作。

于 2012-06-01T10:19:12.467 回答
0

代码看起来正确。一些指示:

  1. 检查 JavaScript 控制台是否有错误?
  2. 检查浏览器的网络视图:服务器会发送什么作为此 AJAX 调用的回复?它有反应吗?
于 2012-06-01T10:19:30.017 回答