如何从CakePhp向Jquery发送ajax响应?

a.t*_*aby 4 cakephp cakephp-2.0 cakephp-2.1

我在视图中有这个脚本:

<script type="text/javascript">
$(document).ready(function() {
    $("#addbrand").click(function() {
        $.ajax({
            url : '../brands/add',
            data : {
                name : "test",
                shortname : "tst"
            },
            dataType : 'json',
            success : function(html, textStatus) {
                alert('Success ' + textStatus + html);
            },
            error : function(xhr, textStatus, errorThrown) {
                alert('An error occurred! ' + errorThrown);
            }
        });
    });
});</script>
Run Code Online (Sandbox Code Playgroud)

在添加控制器我有这些线:

... else if($this->request->is('ajax')){
        if ($this->Brand->save($this->request->query)) {
            // How to send feedback!?
        }else{
            // How to send feedback!?
        }
        $this->autoRender = false;
        exit();
    }
Run Code Online (Sandbox Code Playgroud)

当我点击addbrand时,Ajax操作成功运行,我可以在数据库中看到添加的行,但我不知道如何向用户发送错误或成功消息.我已经阅读了几个教程,但没有一个是关于cakephp2.0,而2.x中的所有内容都有所改变.我还阅读了JSON和XML视图,但不幸的是我什么都不懂!我需要发送状态代码.如果状态是OK,那么我应该发送一系列字符串(实际上是品牌名称),如果状态不正常,我应该发送一个字符串来解释操作未成功完成的原因.如果有人能帮助我,我将非常感激.谢谢


更新:

我改变了代码.我使用了CakeResponse(),现在我的动作是这样的:

if($this->RequestHandler->isAjax()){
        if ($this->Brand->save($this->request->query)) {
            return new CakeResponse(array('body'=> json_encode(array('val'=>'test ok')),'status'=>200));
        }else{
            return new CakeResponse(array('body'=> json_encode(array('val'=>'test not ok')),'status'=>500));
        }
    }
Run Code Online (Sandbox Code Playgroud)

使用CakeResponse我可以很好地处理Jquery中可能的响应.

$("#addbrand").click(function() {
        $.ajax({
            url : '../brands/add',
            data : {
                name : "test",
                shortname : "tst"
            },
            dataType : 'json',
            success : function(data) {
              alert("The brand has been saved");
            },
            error : function(data) {
              alert("Eorror occured");
            },
            complete : function(data) {
                alert($.parseJSON(data.responseText).val);
            }
        });
    });
Run Code Online (Sandbox Code Playgroud)

虽然在我看来现在一切正常,我可以通过Ajax在JSON格式的客户端和服务器之间发送几个变量,我需要知道它是否是在CakePHP中发送Ajax响应的标准方式?这样做还有其他更简单的方法吗?

a.t*_*aby 7

以下几行代码完全return new CakeResponse(array('body'=> json_encode(array('val'=>'test ok')),'status'=>200));符合我的问题:

$this->set('val','test ok');
$this->set('_serialize',array('val'));
$this->response->statusCode(200);
Run Code Online (Sandbox Code Playgroud)

请记住,您需要做两件重要的事情:

  1. 添加Router::parseExtensions('json');到App/Config/routs.php.
  2. 添加var $components = array("RequestHandler");到您的控制器.

我认为这种方式更好,因为你不需要返回任何东西.在之前的解决方案中,我们不得不返回cakeresponse对象,这对于操作的性质感到不安.

  • 为什么要考虑将`Router :: parseExtensions('json');`添加到**lib/Config/routs.php**!? 这是特定于应用程序的逻辑,应该转到App/Config/routes.php. (2认同)