jQuery.parseJSON – Chrome和Safari自动解析JSON

以下函数导致响应变量在Chrome和Safari中为null,但不是Firefox。

function updatePage(response){ // This argument differs by browser response = jQuery.parseJSON(response); for(var i=0; i<response.length; i++){ // conduct magic }; }; 

错误:

 Uncaught TypeError: Cannot read property 'length' of null 

这是因为提供jQuery.parseJSON()除了JSON 字符串之外的任何东西都返回null。 Chrome和Safari似乎会在没有明确请求的情况下自动解析JSON。 如果我在尝试使用jQuery解析之前测试“response”参数,那么它在Chrome和Safari中都已经是一个JSON对象了。 但是,在Firefox中,它仍然是一个字符串。

我想出的唯一解决方案就是通过检查其构造函数来确定是否已经解析了“响应”:

 function updatePage(response){ if(response.constructor === String){ response = jQuery.parseJSON(response); }; for(var i=0; i<response.length; i++){ // conduct magic }; }; 

我错过了什么或者这是目前处理这个问题的唯一方法吗? 似乎jQuery.parseJSON会检测用户代理,并且只是在Chrome / Safari的情况下返回参数。

相关信息

  • 这是jQuery 1.6.1
  • 来自服务器的响应Content-Type是application / json
  • 响应参数源自您的标准jQuery AJAX调用:

 $.ajax({ url: API_URL + queryString + '&limit=' + limit, type: 'GET', cache: false, context: document.body, success: updatePage, error: function(err){ console.log('ERROR: ' + err); } }); 

它不是Chrome或Safari,如果它在响应中看到适当的Content-Type ,它就是jQuery进行解析。 (更新:你添加到问题中的Content-Type是正确的。)我无法立即明白为什么它不会在Firefox上进行。

您可以通过在调用中添加dataType: 'json'来强制它始终进行解析, jQuery.ajax文档中的详细信息。 那么你根本不会调用parseJSONresponse已经是反序列化的对象。