$.ajax option

一、发送到服务器的数据处理

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-8text/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的解析器去解析就会报错。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值