jquery 1.9 .ajax()数据类型默认改变了吗? [英] jquery 1.9 .ajax() datatype default changed?

查看:113
本文介绍了jquery 1.9 .ajax()数据类型默认改变了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出ajax调用,例如:

Given an ajax call such as:

$.ajax(
{
    url:"MyWebService.blah",
    data: {"data":"awesome"},
    success : function(responseText)
    {
       var myJsonObj = $.parseJSON(responseText);
       //do stuff with myJsonObj
    }
});

这个工作正常。我今天将jQuery更新为1.9(我在1.6上暂时)作为Safari的一个可能的修复突然不支持各种切换功能(不再支持eventLayer.X),现在我所有的ajax调用都抛出了以下javascript错误:

This was working fine. I updated jQuery to 1.9 today (I was on 1.6 for a while) as a possible fix to Safari all of the sudden not supporting various toggle functionality (something about eventLayer.X no longer supported), and now all my ajax calls are throwing the following javascript error:

Uncaught Syntax Error: Unexpected token o

经过一些研究和一些测试后,我发现上面代码中的responseText现在是一个JSON对象,而不是字符串。所以这个错误是有道理的,但我试图绕过这个。 jQuery真的改变了默认的返回类型吗?我检查了文档:

After a little research and some testing, I discovered that "responseText" in my code above is now a JSON object, not a string. So the error makes sense, but I'm trying to wrap my head around this. Did jQuery really change the default return type? I checked the documentation:

http://api.jquery.com/jQuery.ajax/

并且dataType默认为Intelligent Guess。我可以看到这可能是多么方便,但我也不喜欢它。

and dataType is defaulted to "Intelligent Guess". I can see how that might be convenient, but I also don't like it.

所以这是我的问题:


  1. 这是jQuery中的一个新的(ish)更改吗?

  2. 是不是版本1.9做了这个,或者之前是这样的,我是一个使用1.6的化石吗?

  3. 有什么建议可以解决这个问题并提出面向未来的代码吗?

这是一个非常根本的变化,会影响很多代码。我将浏览我的代码并删除将我返回的数据解析为JSON的任何实例,但这一切都有点令人不安。我错误地指定了dataType?我认为强制执行dataType而不是依赖于默认值是一个好习惯,但是......哇。我是独自一人,还是jQuery的一个改变是冒昧的?

This is a pretty fundamental change that affects a lot of code. I will go through my code and remove any instance of parsing my returned data to JSON, but this whole thing is a little unnerving. Was I mistaken in not specifying a dataType? I suppose it is a good practice to enforce a dataType instead of relying on default, but... wow. Am I alone on this, or was that a tad presumptuous of a change on the part of jQuery?

推荐答案

jQuery自动检测到什么dataType基于未设置dataType时返回的内容。最有可能1.9只是改进了检测以正确检测你作为json返回的内容。最好始终提供数据类型以确保始终获得一致的结果。

jQuery automatically detects what the dataType is based on what was returned if no dataType was set. Most likely 1.9 just improved that detection to properly detect what you are returning as json. It's best to always give a datatype to ensure you'll always get consistent results.

这篇关于jquery 1.9 .ajax()数据类型默认改变了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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