【问题标题】:CakePHP 3: Ajax response is returning a 200 response code and a parsererrorCakePHP 3:Ajax 响应返回 200 响应代码和解析器错误
【发布时间】:2017-05-27 20:13:24
【问题描述】:

我正在尝试将 ajax 请求从 javascript 文件发送到 cakephp 控制器。 ajax 正在发送一个简单的 json 对象(为了简单起见,我在本例中对其进行了硬编码)。

当我进行日志记录时,服务器能够将 json 字符串解码为一个对象。 $this->Votes->delete 函数调用成功。我的问题是一切正常,但我仍然收到错误消息。

下面是我的代码,下面是我从中得到的输出。

Javascript:

function unvote() {
    $.ajax({
        type: 'POST',
        url: '../votes/unvote',
        async: false,
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify({'post_id':1}),
        success: function(data, textStatus, jqXHR){
            console.log(data);
            console.log(textStatus);
            console.log(jqXHR);
        }.
        error: function(jqXHR, textStatus, errorThrown){
            // this block gets triggered with a 200 response
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        },
    });
}

PHP:投票控制器

public function unvote(){
    $this->autoRender = false;
    $vote = $this->Votes->newEntity();
    if ( $this->request->is('ajax') ) {
        $data = $this->request->input('json_decode');
        $vote = // get the correct vote from the database and save into this object
        if ( $this->Votes->delete($vote) ) {
            $this->response->body('Success');
            $this->response->statusCode(200);
        } else {
            $this->response->body('Failure');
            $this->response->statusCode(500);
        }
    }
    $this->response->type('json');
    return $this->response;
}

ajax 响应:

Object{ readyState=4, responseText="", status=200, statusText="Ok", more...}
parsererror
SyntaxError:JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
> return window.JSON.parse( data + "" );

【问题讨论】:

  • 您是否发送了正确的header("Content-Type: application/json", true);,您为什么要发送window.JSON.parse?因为你期望通过dataType: 'json'json数据,所以会被jquery解析,你不必自己解析。
  • 您的回复无效,请通过浏览器中的 F12 检查请求日志(开发人员控制台 -> 网络选项卡)
  • status=200 与 http 调用有关,而不是与给定数据本身有关。状态 200 在这里表示:发送正确的东西。而已。这与发送的内容无关。
  • 我刚刚添加了 json 标头,仍然具有相同的行为。我正在查看开发者控制台,errorThrown 打印出了关于window.JSON.parse 的部分,但我不知道为什么。
  • 最好查看网络选项卡,在那里查找 ajax 调用 ../votes/unvote 并检查那里的响应数据。或者调用ajax请求,直接在浏览器中获取json数据,如../votes/unvote?post_id=1

标签: javascript php jquery ajax cakephp


【解决方案1】:

jQuery ajax 函数需要一个 json 对象,而您没有给它 json

以下是在 cakephp 中使用 ajax 的一些建议

  • 我不会将自动渲染设置为假。而是创建一个 ajax 布局。
  • 要返回数据,需要设置_serialize视图变量

我建议做这样的事情。

$responseData = ['success' => true];
$this->set('responseData', $responseData);
$this->set('_serialize', ['responseData']);

来自文档的强制性参考

JSON and XML Data Views

您可以通过两种方式生成数据视图。第一个是使用_serialize键,第二个是创建普通模板文件

Using Data Views

_serialize 键是一个特殊的视图变量,它指示在使用数据视图时应该序列化哪些其他视图变量。

【讨论】:

    猜你喜欢
    • 2013-09-08
    • 2019-05-26
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    相关资源
    最近更新 更多