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

Bra*_*cha 6 javascript php ajax jquery 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);
        },
    });
}
Run Code Online (Sandbox Code Playgroud)

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

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

sty*_*yks 2

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

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

  • 我不会将自动渲染设置为 false。相反,创建一个 ajax 布局。
  • 如果要返回数据,则需要设置_serialize视图变量

我建议做这样的事情。

$responseData = ['success' => true];
$this->set('responseData', $responseData);
$this->set('_serialize', ['responseData']);
Run Code Online (Sandbox Code Playgroud)

文档中的强制性参考

JSON 和 XML 数据视图

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

使用数据视图

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