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

时间:2012-09-17 11:27:19

标签: 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>

在添加控制器中我有以下几行:

... 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();
    }

当我点击addbrand时,Ajax操作成功运行,我可以在数据库中看到添加的行,但我不知道如何向用户发送错误或成功消息。我已经阅读了几个教程,但没有一个是关于cakephp2.0而在2.x中一切都改变了。 我也读过JSON and XML views,但不幸的是我什么都不懂! 我需要发送状态代码。如果状态是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));
        }
    }

使用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);
            }
        });
    });

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

2 个答案:

答案 0 :(得分: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);

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

  1. Router::parseExtensions('json');添加到App / Config / routs.php。
  2. var $components = array("RequestHandler");添加到您的控制器。
  3. 我认为这种方式更好,因为你不需要返回任何东西。在之前的解决方案中,我们不得不返回cakeresponse对象,这对于操作的性质感到不安。

答案 1 :(得分:2)

您应该将JSON viewsroute extensions一起使用: 首先,您需要设置路由扩展。这通常用:

完成
Router::parseExtensions('json'); // In App/Config/routes.php

这将使路由器能够处理'json'扩展并知道如何处理如下请求: www.example.com/people/index.json

if($this->RequestHandler->isAjax()){
    if ($this->Brand->save($this->request->query)) {
        //Logic for success
    } else {
       //Logic for save failure
    }
}

此时,您可以选择使用the data views with the serialize key还是使用data view with view files(从CakeBook中复制):

<?php
// Controller code
class PostsController extends AppController {
    public function index() {
        $this->set(compact('posts', 'comments'));
    }
}

// View code - app/View/Posts/json/index.ctp
foreach ($posts as &$post) {
    unset($post['Post']['generated_html']);
}
echo json_encode(compact('posts', 'comments'));

请注意,该视图位于... / Views / Posts / json / ... 你可以在路由器中有多个扩展,这样你就可以返回并处理各种内容 - 毕竟它只是数据表示。

干杯!