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

时间:2022-10-08 08:19:34

I'm attempting to send an ajax request from a javascript file to a cakephp controller. The ajax is sending a simple json object (I've hardcoded it in this example for simplicity).

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

When I do logging, the server is able to decode the json string into an object. The $this->Votes->delete function is called successfully. My problem is that everything works as it should, except I'm still getting an error message anyways.

当我进行日志记录时,服务器能够将json字符串解码为一个对象。成功调用了$this->选票->删除函数。我的问题是,一切都按照它应该的方式运行,除了我仍然得到一条错误消息。

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 + "" );

1 个解决方案

#1


2  

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. Instead create an ajax layout.
  • 我不会把autorender设为false。相反,创建一个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键是一个特殊的视图变量,它指示在使用数据视图时应该序列化哪个其他视图变量。

#1


2  

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. Instead create an ajax layout.
  • 我不会把autorender设为false。相反,创建一个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键是一个特殊的视图变量,它指示在使用数据视图时应该序列化哪个其他视图变量。