0

我有一个应用程序,它使用 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:意外字符'

尽管我将 dataType: 定义为 'json' 并且输出是 PHP 的 json_encode'd。在 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 请求的 dataType 编辑为“文本”(尽管输出是 JSON 格式,甚至标题说它是 JSON 内容),然后成功处理程序运行并且我得到了正确的响应。在这种情况下,当我尝试 $.parseJSON(response) 时会出现同样的问题。

什么地方出了错?我的 JSON 字符串真的无效吗?

4

1 回答 1

2

调试您的响应以查看哪些字符使其无效。将 dataType 设置为 text 并对返回的文本进行转义。

dataType: 'text',
success: function(response){
    console.log(escape(response));
},

您将看到返回的字符,可能是一些奇怪的返回字符导致了问题。

于 2013-10-21T12:24:18.890 回答