gpt4 book ai didi

javascript - CakePHP 3 : Ajax response is returning a 200 response code and a parsererror

转载 作者:可可西里 更新时间:2023-11-01 13:27:29 24 4
gpt4 key购买 nike

我正在尝试将 ajax 请求从 javascript 文件发送到 cakephp Controller 。 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:投票 Controller

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

最佳答案

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

这里有一些在 cakephp 中使用 ajax 的建议

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

我建议做这样的事情。

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

文档中的强制性引用

JSON and XML Data Views

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

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.

关于javascript - CakePHP 3 : Ajax response is returning a 200 response code and a parsererror,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41617960/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com