【问题标题】:How to send ajax response to Jquery from CakePhp?如何从 CakePhp 向 Jquery 发送 ajax 响应?
【发布时间】:2012-09-17 11:27:18
【问题描述】:

我在视图中有这个脚本:

<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 但不幸的是我什么都不懂!!! 我需要发送一个状态码。如果状态正常,那么我应该发送一个字符串数组(实际上是品牌名称),如果状态不正常,我应该发送一个字符串来解释操作未成功完成的原因。 如果有人可以帮助我,我将不胜感激。谢谢


更新:

我更改了代码。我使用 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 响应的标准方式?有没有其他更简单的方法可以做到这一点?

【问题讨论】:

    标签: cakephp cakephp-2.0 cakephp-2.1


    【解决方案1】:

    以下代码行与return new CakeResponse(array('body'=&gt; json_encode(array('val'=&gt;'test ok')),'status'=&gt;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"); 添加到您的控制器。

    我认为这种方式更好,因为您不需要返回任何东西。在以前的解决方案中,我们必须返回 cakeresponse 对象,而这对动作的性质感到不安。

    【讨论】:

    • 为什么要考虑将Router::parseExtensions('json'); 添加到lib/Config/routs.php!?这是特定于应用程序的逻辑,应该转到 App/Config/routes.php 。
    • 是的,我同意你的看法。我自己将它添加到 App/Config/routs.php。我不知道为什么我写的是 lib 而不是 App。这是一个错误。
    • 好的,那么如何使用你序列化的这个响应呢?它变成了 xmlhttp.responseText?我的问题:stackoverflow.com/questions/27979813/… 请!
    【解决方案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/... 你可以在路由器中有多个扩展,这样你就可以返回和处理各种内容——毕竟这只是数据表示。

    干杯!

    【讨论】:

      猜你喜欢
      • 2013-10-23
      • 2020-07-25
      • 2012-04-24
      • 2021-03-10
      • 2013-11-24
      • 2016-12-18
      • 1970-01-01
      • 2014-02-16
      • 2014-09-12
      相关资源
      最近更新 更多