CakePHP 3:Ajax响应返回200响应代码和parsererror

时间:2017-01-12 16:12:21

标签: javascript php jquery ajax cakephp

我正在尝试从javascript文件向cakephp控制器发送ajax请求。 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 + "" );

1 个答案:

答案 0 :(得分:2)

jQuery ajax函数正在期待一个json对象而你并没有给它json

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

  • 我不会将autorender设置为false。而是创建一个ajax布局。
  • 如果要返回数据,则需要设置_serialize视图变量

我建议做这样的事情。

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

来自文档的强制性参考

JSON and XML Data Views

  

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

Using Data Views

  

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

相关问题