一、发送到服务器的数据处理
1. data :发送到服务器的数据; 默认自动转化为字符串;
若data为jsonObj:{key:value},自动转化为格式encodeURIComponent( key ) + "=" + encodeURIComponent( value );
当然如果本身已经是字符串了,就不转换;
换句话说,$.ajax默认情况只传递字符串数据给后台,注意jsonObj会自动字符串化
如果想传字符串之外的数据格式,可以关闭自动转化,通过设置processData为false;
2. processData:默认为true;是控制data自动字符串转化的开关
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
3.contentType: 默认值为“application/x-www-form-urlencoded; charset=UTF-8”
这个字段用来告诉服务器,我的数据的编码格式及类型,是字符串,还是对象;可以为multipart/form-data; charset=UTF-8,text/plain; charset=UTF-8等
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
4.
二、服务端返回的数据处理
1. accepts&dataType&converters
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
s.accepts[ s.dataTypes[ 0 ] ] +
( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
functionajaxConvert( s, response, jqXHR, isSuccess ) {}
当我们定义了dataType,并且dataType的类型在accepts中,则设置Accept头;当拿到服务端返回的数据时,jqXHR会到converters中找到对应的解析器,解析数据;如果解析发生出错,则进入error中,比如你的dataType配置的是json,但实际返回的是jsonp,用json的解析器去解析就会报错。