JQuery 在使用 PHP 的 json_encode 时给出 JSON 语法错误
JQuery gives JSON syntax error when using PHP's json_encode
我有一个应用程序,它使用JQuery $.ajax将JSON编码的数据发送到服务器,在那里我处理它,然后发回同样JSON编码的结果。问题是 JQuery 在我想处理响应时给出了解析错误。(好像PHP的json_encode函数输出无效的JSON格式)。代码如下:
Javascript代码:
$.ajax({
type: 'POST',
url: URL+'pages/processListUIAjaxRequest',
data:{filters: filters, rebuild_params: $('#rebuild_params''['+unique+''']').val()},
dataType: 'json',
success: function(response){
alert(response);
},
error: function(request, status, error){
alert('Unable to update table contents');
console.log(request);
console.log(status);
console.log(error);
}
});
这是一段输出响应的 PHP 代码:
$response->addResult($uFilters);
header('Content-Type: application/json');
$response->toJSON(true);
$uFilters是一个简单的数组,$response对象的toJSON方法在这里:
public function toJSON($output = false){
$out = array();
if($this->hasErrors()){
$out['has_error'] = true;
$out['errors'] = $this->getErrors();
} else $out['has_error'] = false;
$out['result'] = $this->_result;
if($output){
echo json_encode($out);
}else{
return json_encode($out);
}
}// toJSON
每次运行代码时,我都会得到"无法更新表内容",并且在 JavaScript 控制台上我有:
'语法错误: JSON.parse: 意外字符'
尽管我将数据类型:定义为"json",并且输出由 PHP json_encode。在 JavaScript 控制台上,我可以看到响应文本是:
"{"has_error":false,"result":{"page_id":"xxx"}}"
尝试复制它并使用在线 JSON 验证器工具进行验证,有趣的是它有效了几次,几次无效(没有任何一致性)我有点困惑。尝试使用其他标头,例如:
header('Content-Type: text/json');
header('Content-Type:javascript/json');
header('Content-Type: application/json');
或者没有标题,但什么都没有。
如果我将 JQuery ajax 请求的数据类型编辑为"文本"(尽管输出是 JSON 格式的,甚至标头都说它是一个 JSON 内容),那么成功处理程序就会运行并且我得到了正确的响应。在这种情况下,当我尝试 $.parseJSON(response) 时,会出现同样的问题。
出了什么问题?我的 JSON 字符串真的无效吗?
调试您的响应以查看哪些字符使其无效。将数据类型设置为文本并转义返回的文本。
dataType: 'text',
success: function(response){
console.log(escape(response));
},
您将看到返回的字符,可能有一些奇怪的返回字符正在解决问题。
相关文章:
- ajax和json错误.php帖子错误
- json错误消息,可以't请参阅SyntaxError
- json错误json.parse:意外的数据结束错误
- 如何处理JSON错误消息
- D3.js 制作树时的 json 错误
- 评估 json 错误
- 使用 Web API MS CRM 时的 JSON 错误
- Javascript/JSON 错误:格式不正确
- JSON 错误:无法读取未定义的属性“xxx”
- 如何序列化全日历源.将循环结构转换为 JSON 错误
- jquery json错误,当我想从Steam市场获取JSON时
- Facebook javascript JSON 错误消息
- 控制台中的JSON错误:意外的令牌:
- 如何摆脱Firefox中的JSON错误
- 使用jQuery$.each,Json错误,结果为1
- 文件不存在错误,package.json错误
- JSON错误:应为..得到'未定义'
- 节点js中的JSON错误未定义为发布数据的前缀
- php后端出现JSON错误
- Jquery Json错误,来自steam的Json,访问控制允许来源