简体   繁体   English

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

[英]CakePHP 3: Ajax response is returning a 200 response code and a parsererror

I'm attempting to send an ajax request from a javascript file to a cakephp controller. 我正在尝试将Ajax请求从JavaScript文件发送到Cakephp控制器。 The ajax is sending a simple json object (I've hardcoded it in this example for simplicity). Ajax正在发送一个简单的json对象(为简单起见,我在此示例中已对其进行硬编码)。

When I do logging, the server is able to decode the json string into an object. 当我进行日志记录时,服务器能够将json字符串解码为一个对象。 The $this->Votes->delete function is called successfully. $this->Votes->delete函数被成功调用。 My problem is that everything works as it should, except I'm still getting an error message anyways. 我的问题是,一切正常,但无论如何我仍然收到错误消息。

Below is my code, and below that is the output that I get from it. 下面是我的代码,下面是我从代码中获得的输出。

Javascript: 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: Votes Controller 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 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 + "" );

jQuery ajax function is expecting a json object and you aren't giving it json jQuery ajax函数期望一个json对象,而您没有给它json

Here are some suggestions for working with ajax in cakephp 这是在cakephp中使用ajax的一些建议

  • I wouldn't set autorender to false. 我不会将autorender设置为false。 Instead create an ajax layout. 而是创建一个ajax布局。
  • You need to set the _serialize view variable if you want to return data 如果要返回数据,则需要设置_serialize视图变量

I would suggest doing something like this. 我建议做这样的事情。

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

Obligatory references from the docs 来自文档的强制性参考

JSON and XML Data Views JSON和XML数据视图

There are two ways you can generate data views. 您可以通过两种方式生成数据视图。 The first is by using the _serialize key, and the second is by creating normal template files 第一个是通过使用_serialize键,第二个是通过创建常规模板文件

Using Data Views 使用数据视图

The _serialize key is a special view variable that indicates which other view variable(s) should be serialized when using a data view. _serialize键是一个特殊的视图变量,它指示使用数据视图时应序列化哪些其他视图变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM