为什么'jQuery.parseJSON'没有必要?

时间:2021-10-21 03:53:57

i'm doing an ajax request with query and wondering why my response is already a JS object.

我正在使用查询执行ajax请求,并想知道为什么我的响应已经是JS对象。

If i do a

如果我做了

var obj = jQuery.parseJSON(response);

'obj' is null, but i can use 'response' as an array of js objects.

'obj'为null,但我可以使用'response'作为js对象的数组。

This is not really a problem, but i would like to understand this behavior.

这不是一个真正的问题,但我想了解这种行为。

Thanks

谢谢

5 个解决方案

#1


10  

This happens when you make an AJAX call and specify the dataType JSON jQuery calls jQuery.parseJSON on the response for you. In fact you can specify what function to call depending on the dataType as you can se from the documentation

当您进行AJAX调用并指定dataType时,会发生这种情况.JSON jQuery会在响应中为您调用jQuery.parseJSON。实际上,您可以根据dataType指定要调用的函数,您可以从文档中进行选择

converters(added 1.5)
Map Default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML} A map of dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response

转换器(添加1.5)Map默认值:{“* text”:window.String,“text html”:true,“text json”:jQuery.parseJSON,“text xml”:jQuery.parseXML} dataType-to-map dataType转换器。每个转换器的值都是一个返回响应转换值的函数

So if you make a call like this

所以,如果你打这样的电话

$.ajax({
  url: yoururl,
  dataType: "json",
  success: function(data){
    //data is already a json
  }

If you don't specify a dataType jQuery tries to guess it

如果你没有指定dataType,jQuery会尝试猜测它

dataTypeString Default: Intelligent Guess (xml, json, script, or html)

dataTypeString默认值:智能猜测(xml,json,script或html)

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

您期望从服务器返回的数据类型。如果没有指定,jQuery将尝试根据响应的MIME类型推断它(XML MIME类型将产生XML,在1.4 JSON中将产生一个JavaScript对象,在1.4脚本中将执行脚本,其他任何东西将是以字符串形式返回)。可用的类型(以及作为成功回调的第一个参数传递的结果)是:

"xml": Returns a XML document that can be processed via jQuery.
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM. "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests. "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "
=[TIMESTAMP]", to the URL unless the cache option is set to true.
"text": A plain text string. multiple, space-separated values:
As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.

“xml”:返回可以通过jQuery处理的XML文档。 “html”:以纯文本形式返回HTML;包含的脚本标记在插入DOM时进行评估。 “script”:将响应评估为JavaScript并将其作为纯文本返回。通过将查询字符串参数“= [TIMESTAMP]”附加到URL来禁用缓存,除非缓存选项设置为true。注意:这会将POST转换为GET以获取远程域请求。 “json”:将响应计算为JSON并返回JavaScript对象。在jQuery 1.4中,JSON数据以严格的方式解析;任何格式错误的JSON都会被拒绝,并抛出一个解析错误。 (有关正确的JSON格式化的更多信息,请参阅json.org。)“jsonp”:使用JSONP加载JSON块。添加一个额外的“?callback =?”到URL的末尾以指定回调。通过将查询字符串参数“= [TIMESTAMP]”附加到URL来禁用缓存,除非缓存选项设置为true。 “text”:纯文本字符串。多个空格分隔值:从jQuery 1.5开始,jQuery可以将dataType从Content-Type标头中收到的数据转换为您需要的数据类型。例如,如果要将文本响应视为XML,请对dataType使用“text xml”。您还可以发出JSONP请求,将其作为文本接收,并由jQuery解释为XML:“jsonp text xml”。类似地,诸如“jsonp xml”之类的速记字符串将首先尝试从jsonp转换为xml,如果失败,则从jsonp转换为text,然后从text转换为xml。

#2


4  

It pretty much depends which dataType you pass into your jQuery ajax request. This might happen implict by calling .getJSON() or directly using $.ajax().

它几乎取决于您传递给jQuery ajax请求的dataType。这可能通过调用.getJSON()或直接使用$ .ajax()来实现。

However, if you omit the dataType, jQuery trys to do some magic and guesses which data was received. As for JSON data, it uses a simple regular expression to check if a response looks like a JSON-string and if so, it automatically parses it for you. jQuery will try to infer it based on the MIME type of the response.

但是,如果省略dataType,jQuery会尝试做一些魔术并猜测接收到哪些数据。对于JSON数据,它使用一个简单的正则表达式来检查响应是否看起来像JSON字符串,如果是,它会自动为您解析它。 jQuery将尝试根据响应的MIME类型推断它。

So always be precise and tell jQuery which type of data you expect.

因此,请务必准确地告诉jQuery您期望的数据类型。

#3


2  

The default behaviour of jQuery's ajax method is to analyse the response and return it as the most appropriate data type. If your response looks like JSON, therefore, it will be converted to a JavaScript object/array.

jQuery的ajax方法的默认行为是分析响应并将其作为最合适的数据类型返回。因此,如果您的响应看起来像JSON,它将被转换为JavaScript对象/数组。

You can override this behaviour by setting the dataType attribute in the ajax settings.

您可以通过在ajax设置中设置dataType属性来覆盖此行为。

#4


2  

if you specify the dataType as json the jquery parses the response for you like

如果你将dataType指定为json,则jquery会为你解析响应

$.ajax({
...
dataType:'json',
...
});

same is the case with jQuery.getJSON()

jQuery.getJSON()的情况也是如此

this is how the source code for getJSON looks like

这就是getJSON的源代码的样子

getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},

https://github.com/jquery/jquery/blob/master/src/ajax.js#L283

https://github.com/jquery/jquery/blob/master/src/ajax.js#L283

#5


1  

Because

因为

jQuery.ajaxSettings.converters["text json"] === jQuery.parseJSON

I.E it will run the function everytime json response is detected automatically or explicitly set by yourself

I.E每次json响应被自动检测或自己明确设置时,它将运行该功能

#1


10  

This happens when you make an AJAX call and specify the dataType JSON jQuery calls jQuery.parseJSON on the response for you. In fact you can specify what function to call depending on the dataType as you can se from the documentation

当您进行AJAX调用并指定dataType时,会发生这种情况.JSON jQuery会在响应中为您调用jQuery.parseJSON。实际上,您可以根据dataType指定要调用的函数,您可以从文档中进行选择

converters(added 1.5)
Map Default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML} A map of dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response

转换器(添加1.5)Map默认值:{“* text”:window.String,“text html”:true,“text json”:jQuery.parseJSON,“text xml”:jQuery.parseXML} dataType-to-map dataType转换器。每个转换器的值都是一个返回响应转换值的函数

So if you make a call like this

所以,如果你打这样的电话

$.ajax({
  url: yoururl,
  dataType: "json",
  success: function(data){
    //data is already a json
  }

If you don't specify a dataType jQuery tries to guess it

如果你没有指定dataType,jQuery会尝试猜测它

dataTypeString Default: Intelligent Guess (xml, json, script, or html)

dataTypeString默认值:智能猜测(xml,json,script或html)

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

您期望从服务器返回的数据类型。如果没有指定,jQuery将尝试根据响应的MIME类型推断它(XML MIME类型将产生XML,在1.4 JSON中将产生一个JavaScript对象,在1.4脚本中将执行脚本,其他任何东西将是以字符串形式返回)。可用的类型(以及作为成功回调的第一个参数传递的结果)是:

"xml": Returns a XML document that can be processed via jQuery.
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM. "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests. "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "
=[TIMESTAMP]", to the URL unless the cache option is set to true.
"text": A plain text string. multiple, space-separated values:
As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.

“xml”:返回可以通过jQuery处理的XML文档。 “html”:以纯文本形式返回HTML;包含的脚本标记在插入DOM时进行评估。 “script”:将响应评估为JavaScript并将其作为纯文本返回。通过将查询字符串参数“= [TIMESTAMP]”附加到URL来禁用缓存,除非缓存选项设置为true。注意:这会将POST转换为GET以获取远程域请求。 “json”:将响应计算为JSON并返回JavaScript对象。在jQuery 1.4中,JSON数据以严格的方式解析;任何格式错误的JSON都会被拒绝,并抛出一个解析错误。 (有关正确的JSON格式化的更多信息,请参阅json.org。)“jsonp”:使用JSONP加载JSON块。添加一个额外的“?callback =?”到URL的末尾以指定回调。通过将查询字符串参数“= [TIMESTAMP]”附加到URL来禁用缓存,除非缓存选项设置为true。 “text”:纯文本字符串。多个空格分隔值:从jQuery 1.5开始,jQuery可以将dataType从Content-Type标头中收到的数据转换为您需要的数据类型。例如,如果要将文本响应视为XML,请对dataType使用“text xml”。您还可以发出JSONP请求,将其作为文本接收,并由jQuery解释为XML:“jsonp text xml”。类似地,诸如“jsonp xml”之类的速记字符串将首先尝试从jsonp转换为xml,如果失败,则从jsonp转换为text,然后从text转换为xml。

#2


4  

It pretty much depends which dataType you pass into your jQuery ajax request. This might happen implict by calling .getJSON() or directly using $.ajax().

它几乎取决于您传递给jQuery ajax请求的dataType。这可能通过调用.getJSON()或直接使用$ .ajax()来实现。

However, if you omit the dataType, jQuery trys to do some magic and guesses which data was received. As for JSON data, it uses a simple regular expression to check if a response looks like a JSON-string and if so, it automatically parses it for you. jQuery will try to infer it based on the MIME type of the response.

但是,如果省略dataType,jQuery会尝试做一些魔术并猜测接收到哪些数据。对于JSON数据,它使用一个简单的正则表达式来检查响应是否看起来像JSON字符串,如果是,它会自动为您解析它。 jQuery将尝试根据响应的MIME类型推断它。

So always be precise and tell jQuery which type of data you expect.

因此,请务必准确地告诉jQuery您期望的数据类型。

#3


2  

The default behaviour of jQuery's ajax method is to analyse the response and return it as the most appropriate data type. If your response looks like JSON, therefore, it will be converted to a JavaScript object/array.

jQuery的ajax方法的默认行为是分析响应并将其作为最合适的数据类型返回。因此,如果您的响应看起来像JSON,它将被转换为JavaScript对象/数组。

You can override this behaviour by setting the dataType attribute in the ajax settings.

您可以通过在ajax设置中设置dataType属性来覆盖此行为。

#4


2  

if you specify the dataType as json the jquery parses the response for you like

如果你将dataType指定为json,则jquery会为你解析响应

$.ajax({
...
dataType:'json',
...
});

same is the case with jQuery.getJSON()

jQuery.getJSON()的情况也是如此

this is how the source code for getJSON looks like

这就是getJSON的源代码的样子

getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},

https://github.com/jquery/jquery/blob/master/src/ajax.js#L283

https://github.com/jquery/jquery/blob/master/src/ajax.js#L283

#5


1  

Because

因为

jQuery.ajaxSettings.converters["text json"] === jQuery.parseJSON

I.E it will run the function everytime json response is detected automatically or explicitly set by yourself

I.E每次json响应被自动检测或自己明确设置时,它将运行该功能