【发布时间】:2017-05-27 20:13:24
【问题描述】:
我正在尝试将 ajax 请求从 javascript 文件发送到 cakephp 控制器。 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 + "" );
【问题讨论】:
-
您是否发送了正确的
header("Content-Type: application/json", true);,您为什么要发送window.JSON.parse?因为你期望通过dataType: 'json'json数据,所以会被jquery解析,你不必自己解析。 -
您的回复无效,请通过浏览器中的 F12 检查请求日志(开发人员控制台 -> 网络选项卡)
-
status=200与 http 调用有关,而不是与给定数据本身有关。状态 200 在这里表示:发送正确的东西。而已。这与发送的内容无关。 -
我刚刚添加了 json 标头,仍然具有相同的行为。我正在查看开发者控制台,
errorThrown打印出了关于window.JSON.parse的部分,但我不知道为什么。 -
最好查看网络选项卡,在那里查找 ajax 调用
../votes/unvote并检查那里的响应数据。或者调用ajax请求,直接在浏览器中获取json数据,如../votes/unvote?post_id=1
标签: javascript php jquery ajax cakephp