与cakephp简单的json响应

时间:2014-06-07 10:11:50

标签: ajax json cakephp

我试图将一些json传递给cakePHP 2.5中的控制器并再次返回它,以确保它完全正常。

然而我没有回复内容。只有200个成功。从阅读文档我的印象是,如果我传递一些json,那么responseHandler将返回json作为响应。

不确定我错过了什么。

传递数据

var neworderSer = $(this).sortable("serialize");

给出了

item[]=4&item[]=3&item[]=6&item[]=5&item[]=7 

appController.php

public $components = array(
    'DebugKit.Toolbar', 
    'Search.Prg', 
    'Session', 
    'Auth',
    'Session',
    'RequestHandler'
);

index.ctp

    $.ajax({
        url: "/btstadmin/pages/reorder",
        type: "post",
        dataType:"json",
        data: neworderSer,
        success: function(feedback) {
            notify('Reordered pages');
        },
        error: function(e) {
            notify('Reordered pages failed', {
                status: 'error'
            });
        }
    });

PagesController.php

public function reorder() {

    $this->request->onlyAllow('ajax');
    $data = $this->request->data;
    $this->autoRender = false;
    $this->set('_serialize', 'data');

}

更新: 我现在已将以下内容添加到routes.php

    Router::parseExtensions('json', 'xml');

我已将控制器更新为

    $data = $this->request->data;

    $this->set("status", "OK");
    $this->set("message", "You are good");
    $this->set("content", $data);
    $this->set("_serialize", array("status", "message", "content"));

现在一切都很完美。

2 个答案:

答案 0 :(得分:7)

应提供正确的Accept标题或扩展名

为了让请求处理程序能够选择正确的视图,您需要发送相应的Accept标题(application/json),或提供扩展名,在您的情况下{{1 }}。并且为了能够识别扩展,需要启用扩展解析。

请参阅http://book.cakephp.org/...views.html#enabling-data-views-in-your-application

视图仅序列化视图变量

JSON视图仅自动序列化视图变量,并且从您显示的代码看起来您​​似乎没有设置名为.json的视图变量。

请参阅http://book.cakephp.org/...views.html#using-data-views-with-the-serialize-key

需要呈现视图

除非你有充分的理由,否则你不应该禁用auto rendering,并且在你的情况下最终也会手动调用data。目前,您的操作甚至都不会尝试渲染任何内容。

CakeRequest :: onlyAllow()用于HTTP方法

Controller:render()(btw为deprecated as of CakePHP 2.5)用于指定允许的CakeRequest::onlyAllow()方法,即HTTPGETPOST等虽然使用任何可用的探测器(例如PUT)都可以使用,但您可能不应该依赖它。

长话短说

您的ajax方法应该更像这样:

reorder()

最后,如果您不想/不能使用public function reorder() { if(!$this->request->is('ajax')) { throw new BadRequestException(); } $this->set('data', $this->request->data); $this->set('_serialize', 'data'); } 标头,则需要将Accept扩展名附加到AJAX请求的网址:< / p>

.json

并因此在url: "/btstadmin/pages/reorder.json" 中启用扩展解析,如:

routes.php

PS

有关在不使用扩展程序的情况下使用JSON视图的方法,请参阅 Cakephp REST API remove the necessity of .format

答案 1 :(得分:0)

输出您的json数据

public function reorder() {

$this->request->onlyAllow('ajax');
$data = $this->request->data;
$this->autoRender = false;
$this->set('_serialize', 'data');
echo json_encode($data);

}
相关问题