【发布时间】:2011-06-21 13:43:24
【问题描述】:
以下函数导致响应变量在 Chrome 和 Safari 中为空,但在 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 string 以外的任何内容都会返回 null。似乎 Chrome 和 Safari 会自动解析 JSON,而无需明确请求。如果我在尝试使用 jQuery 解析它之前测试“响应”参数,它已经是 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);
}
});
【问题讨论】: