以下函数导致响应变量在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
};
};
Run Code Online (Sandbox Code Playgroud)
错误:
Uncaught TypeError: Cannot read property 'length' of null
Run Code Online (Sandbox Code Playgroud)
这是因为提供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
};
};
Run Code Online (Sandbox Code Playgroud)
我错过了什么或者这是目前处理这个问题的唯一方法吗?好像jQuery.parseJSON将检测用户代理和刚刚回归的说法是,是在Chrome/Safari浏览器的情况下.
相关信息
$.ajax({
url: API_URL + queryString + '&limit=' + limit,
type: 'GET',
cache: false,
context: document.body,
success: updatePage,
error: function(err){
console.log('ERROR: ' + err);
}
});
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 15
它不是Chrome或Safari,如果它Content-Type在响应中看到合适的话,那就是jQuery进行解析.(更新:Content-Type你已经添加到问题中是正确的.)我无法立即明白为什么它不会在Firefox上进行.
你可以迫使它总是加做解析dataType: 'json'您的来电,详细的jQuery.ajax文档.然后你根本不会打电话parseJSON,response已经是反序列化的对象.