与cakephp简单的json响应

Kei*_*wer 3 ajax json cakephp

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

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

不确定我错过了什么.

数据被传递

var neworderSer = $(this).sortable("serialize");
Run Code Online (Sandbox Code Playgroud)

这使

item[]=4&item[]=3&item[]=6&item[]=5&item[]=7 
Run Code Online (Sandbox Code Playgroud)

appController.php

public $components = array(
    'DebugKit.Toolbar', 
    'Search.Prg', 
    'Session', 
    'Auth',
    'Session',
    'RequestHandler'
);
Run Code Online (Sandbox Code Playgroud)

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'
            });
        }
    });
Run Code Online (Sandbox Code Playgroud)

PagesController.php

public function reorder() {

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

}
Run Code Online (Sandbox Code Playgroud)

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

    Router::parseExtensions('json', 'xml');
Run Code Online (Sandbox Code Playgroud)

我已将控制器更新为

    $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"));
Run Code Online (Sandbox Code Playgroud)

现在一切都很完美.

ndm*_*ndm 7

Accept应提供适当的标题或扩展名

为了使请求处理程序能够选择正确的视图,您需要在您的情况下发送适当的Acceptheader(application/json)或提供扩展.json.并且为了完全识别扩展,需要启用扩展解析.

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

该视图仅序列化视图变量

JSON视图仅自动序列化视图变量,并且从您显示的代码看起来不像您设置了一个名为的视图变量data.

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

需要呈现视图

除非有充分的理由,否则不应禁用自动渲染,并且在您的情况下也最终Controller:render()手动调用.目前,您的操作甚至都不会尝试渲染任何内容.

CakeRequest :: onlyAllow()用于HTTP方法

CakeRequest::onlyAllow()(顺便说一句这是不赞成的CakePHP 2.5)是用于指定允许的HTTP方法,即GET,POST,PUT,等在使用任何类似例如可用的检测器ajax将工作,你可能不应该依赖于它.

长话短说

你的reorder()方法看起来应该更像这样:

public function reorder() {
    if(!$this->request->is('ajax')) {
        throw new BadRequestException();
    }
    $this->set('data', $this->request->data);
    $this->set('_serialize', 'data');
}
Run Code Online (Sandbox Code Playgroud)

最后,如果您不想/不能使用Accept标头,您需要将.json扩展名附加到AJAX请求的URL:

url: "/btstadmin/pages/reorder.json"
Run Code Online (Sandbox Code Playgroud)

并因此在您的routes.php喜欢中启用扩展解析:

Router::parseExtensions('json');
Run Code Online (Sandbox Code Playgroud)

PS

请参阅Cakephp REST API,删除.format的必要性,了解如何在不使用扩展的情况下使用JSON视图.