JQuery 在使用 PHP 的 json_encode 时给出 JSON 语法错误

JQuery gives JSON syntax error when using PHP's json_encode

本文关键字:JSON 错误 语法 encode PHP json JQuery      更新时间:2023-09-26

我有一个应用程序,它使用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));
},

您将看到返回的字符,可能有一些奇怪的返回字符正在解决问题。