jQuery.parseJSON-Chrome和Safari自动解析JSON [英] jQuery.parseJSON - Chrome and Safari automatically parsing JSON

查看:198
本文介绍了jQuery.parseJSON-Chrome和Safari自动解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下功能导致响应变量在Chrome和Safari中为空,但在Firefox中为空.

The following function results in the response variable being null in Chrome and Safari but not 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

这是因为除了JSON string 以外,向jQuery.parseJSON()提供任何内容都会返回null.似乎Chrome和Safari无需明确请求即可自动解析JSON.如果我在尝试使用jQuery解析响应"参数之前对其进行了测试,那么它在Chrome和Safari中已经是一个JSON对象.但是,在Firefox中,它仍然是字符串.

This is because feeding jQuery.parseJSON() anything but a JSON string returns null. It seems Chrome and Safari automatically parse JSON without explicitly being requested. If I test the "response" argument before trying to parse it with jQuery, it's already a JSON object in both Chrome and Safari. However, in Firefox it's still a string.

我想在所有浏览器中处理此问题的唯一解决方案是通过检查其响应器的构造来确定响应"是否已被解析:

The only solution I've come up with to handle this across browsers is to determine if "response" has already been parsed by checking its constructor:

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,仅按原样返回参数.

Am I missing something or is this the only way to handle this currently? Seems like jQuery.parseJSON would detect the user-agent and just return the argument as-is in the case of 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上运行.

It's not Chrome or Safari, it's jQuery that does the parsing if it sees the appropriate Content-Type on the response. (Update: And the Content-Type you've added to the question is correct.) I can't immediately see why it wouldn't be doing it on Firefox.

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

You can force it to always do the parsing by adding dataType: 'json' to your call, details in the jQuery.ajax docs. Then you wouldn't call parseJSON at all, response would already be the deserialized object.

这篇关于jQuery.parseJSON-Chrome和Safari自动解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆