浅谈ajax中的json

首先我们来看下几个重要参数的说明:

data

类型:String

发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。必须为 Key/Value 格式。如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 '&foo=bar1&foo=bar2'。

dataType

类型:String

预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息来智能判断,比如 XML MIME 类型就被识别为 XML。在 1.4 中,JSON 就会生成一个 JavaScript 对象,而 script 则会执行这个脚本。随后服务器端返回的数据会根据这个值解析后,传递给回调函数。可用值:

  • "xml": 返回 XML 文档,可用 jQuery 处理。
  • "html": 返回纯文本 HTML 信息;包含的 script 标签会在插入 dom 时执行。
  • "script": 返回纯文本 JavaScript 代码。不会自动缓存结果。除非设置了 "cache" 参数。注意:在远程请求时(不在同一个域下),所有 POST 请求都将转为 GET 请求。(因为将使用 DOM 的 script标签来加载)
  • "json": 返回 JSON 数据 。
  • "jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。
  • "text": 返回纯文本字符串

在设置ajax参数的时候,如果data不为string,将会调用Jquery.param将data转换为string

jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, valueOrFunction ) {

// If value is a function, invoke it and use its return value
var value = isFunction( valueOrFunction ) ?
valueOrFunction() :
valueOrFunction;

s[ s.length ] = encodeURIComponent( key ) + "=" +
encodeURIComponent( value == null ? "" : value );
};

// If an array was passed in, assume that it is an array of form elements.
if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {

// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
} );

} else {

// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}

也就是说前端在和后端进行数据传输时,data会被转换成string。

 当datatype为json的时候,其实后台会把data转换成json字符串,然后在ajax中执行ajaxConvert。

function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},

// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();

// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}

current = dataTypes.shift();

// Convert to each sequential dataType
while ( current ) {

if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}

// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}

prev = current;
current = dataTypes.shift();

if ( current ) {

// There's only work to do if current dataType is non-auto
if ( current === "*" ) {

current = prev;

// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {

// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];

// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {

// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {

// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {

// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];

// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}

// Apply converter (if not an equivalence)
if ( conv !== true ) {

// Unless errors are allowed to bubble, catch and return them
if ( conv && s.throws ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return {
state: "parsererror",
error: conv ? e : "No conversion from " + prev + " to " + current
};
}
}
}
}
}
}

return { state: "success", data: response };
}

其中

converters: {

// Convert anything to text
"* text": String,

// Text to html (true = no transformation)
"text html": true,

// Evaluate text as a json expression
"text json": JSON.parse,

// Parse text as xml
"text xml": jQuery.parseXML
},

当datatype为json的时候,最终会调用JSON.parse解析得到的json字符串,返回json对象到success方法里面。

原文地址:https://www.cnblogs.com/Ferrari/p/8572778.html