jQuery-1.9.1 Source Analysis Series (16) ajax--response data processing and API grooming

Source: Internet
Author: User
Tags http post text to json

Ajax will do two things in response to a request: Get response data and convert data using type converter

A. Getting response data

The get response data is called by the ajaxhandleresponses function to handle.

The ajaxhandleresponses features are:

-Set all responsexxx fields for JQXHR (value is response data)

-Find the right datatype (one of both in Content-type and expected datatype)

-Returns the correct response data

Let's look at a format for the response data:

responses ="{" Code ": $," data ": null," message ":" All Exist "," sessionId ":" Wsdfhl333sdfs "}"
  }

  Set RESPONSEXXX There are only two responsexml and ResponseText

    // fill in the Responsexxx (responsexml/responsetext) field,     for inch responsefields) {        if in responses) {            = responses[type];}    }

Find the right datatype. It's a process of probing

    //remove the automatically added datatype type and get Content-type type in the process     while(datatypes[0] = = = "*") {datatypes.shift (); if(ct = = =undefined) {CT= S.mimetype | | Jqxhr.getresponseheader ("Content-type"); }    }    //Check if we are working on a known content-type    if(CT) { for(Typeinchcontents) {            if(contents[type] &&contents[type].test (CT))                {Datatypes.unshift (type);  Break; }        }    }    //Check to see if we have the expected data type response    if(datatypes[0]inchresponses) {Finaldatatype= datatypes[0 ]; } Else {        //to try a convertible data type         for(Typeinchresponses) {            if(!datatypes[0] | | s.converters[type + "" + datatypes[0]]) {Finaldatatype=type;  Break; }            if( !Firstdatatype) {Firstdatatype=type; }        }        //Or just use first oneFinaldatatype = Finaldatatype | |Firstdatatype; }

Returns the correct response data

    // if we find a datatype    // put datatype in the datatypes, if you need to.    // return the corresponding response data    if (finaldatatype) {        if (Finaldatatype!== datatypes[0 ]) {            Datatypes.unshift (fin Aldatatype);         return  responses[Finaldatatype]; }}

B. type converter

Ajax has four types of converters

 converters: { //  any content is converted to a string  //  window. The String will be compressed in the min file to a.string  "* text" : Window. String,  //  text is converted to HTML (true means no conversion is required, return directly  text HTML: true   //  text to JSON object  "text json" : Jquery.parsejson,  //  text to Xml "Text xml" : Jquery.parsexml}  

Where jquery.parsejson/jquery.parsexml Click to see details

Besides, there's a special extension for script.

 //  Ajax request Set default value  jquery.ajaxsetup ({ /*  * *     The content type sends the request header (Content-type), which notifies the server what type of return results the request needs to receive.     * If the accepts setting needs to be modified, it is recommended to set it once in the $.ajaxsetup () method. * @type {Object}  */  accepts: {SCR IPT:  "Text/javascript, Application/javascript, Application/ecmascript, application/x-ecmascript" }, Contents: {script: /(?: JAVA|ECMA) Script/  "Text script" : function              (text) {jquery.globaleval (text);         return   text; }}

There is also a time when the JSONP is preprocessed.

            function () {                if (!  Responsecontainer) {                    + "is not called" );                }                 return responsecontainer[0 ];            };

DataType is nothing more than a few cases.

  1:datatype is empty, automatic conversion

At this point jquery can only guess the type that is currently being processed (Ajaxhandleresponses) based on the message header information

// Remove the PASS datatype and get the returned Content-type  while (Datatypes[0] = = = "*") {    datatypes.shift (    ); if (ct = = = undefined        ) {= S.mimetype | | jqxhr.getresponseheader ("content-type");}    }

The message header information is obtained by Xhr.getallresponseheaders () and then matched to the values of all Content-type objects.

Of course Find this content-type = "html", we also have to see if there is a corresponding processing method, if there is a need to replace this datatypes (ajaxhandleresponses)

// See if we can deal with the content-type, the binary type of this kind of chip is not good to deal with if (CT) {    //  can actually handle text, XML, and JSON for in      contents) {         if (Contents[type] && contents[type].test (CT)) {            datatypes.unshift (type);              Break ;        }    }}

After this process, datatypes would have been a corresponding HTML, which is the automatic conversion process within jquery.

  2:datatype Developer Designation

  XML, JSON, script, HTML, JSOP

  

Eventually Ajax succeeds in unifying the call Ajaxconvert function processing. So the converter sums it up in a nutshell: The type converter converts the ResponseText or responsexml of the service-side response to the data type specified at the time of the request datatype, if no type is specified, it is automatically processed according to the response header Content-type. The converter that selects the response based on the target type is converted to the target data.

  

C. jQuery Ajaxsetup (target[, Settings])

function if used for external use without settings This parameter: Used to set The global default for AJAX.

There are two uses of this function

1. When target, settings two parameters are passed, create a fully fledged set object (containing the ajaxsettings and the passed settings) written to target. Finally jquery.ajaxsettings this global variable does not change. This usage is primarily used within jquery, and external use is meaningless.

2. When the settings does not exist (that is, there is only one parameter), the target is written to jquery.ajaxsettings. This usage is more externally used. The main setting is the global default setting for Ajax.

View Source

// creates a fully fledged set object (containing Ajaxsettings and passed settings) written to target.  // If settings is omitted, target is written to ajaxsettings. function (target, settings) {    return settings?         Ajaxextend (Target, jquery.ajaxsettings), settings):        jquery.ajaxsettings, target);}

Using the Ajaxextend function, the jQuery.ajaxSettings.flatOptions specifies that those options do not extend deep (deep copy substitution), and others do deep expansion. The default option for no depth expansion is only two jQuery.ajaxSettings.flatOptions: {url:true,context:true}. externally, you can add options that do not extend depth directly to the JQuery.ajaxSettings.flatOptions .

//extended functions specifically for AJAX options//options inside the flatoptions (no depth extension required (deep copy replacement))functionajaxextend (target, SRC) {varDeep , key, Flatoptions= JQuery.ajaxSettings.flatOptions | | {}; //for options that do not require deep expansion, save in Target[key], the option to expand in depth is saved in Deep[key].      for(Keyinchsrc) {        if(src[key]!==undefined) {(flatoptions[key]? Target: (Deep | | (deep = {})) ) [Key] =src[Key]; }    }    //extend deep depth (deep copy replacement) to target    if(deep) {Jquery.extend (true, target, deep); }    returnTarget;}

D. Ajax-related APIs

jquery.get (URL [, data] [, success] [, type]) ( function is used to through HTTP GET form of AJAX request to get remote data.

The Jquery.get () function is used to implement a simple get form of an AJAX request, which is implemented using Jquery.ajax () at the bottom, but omits most of the infrequently used parameter settings and is limited to the HTTP GET method. Note that the function is loading data asynchronously . The Jquery.get () described here is a global approach (called without creating a jquery object, which you can understand as a static function). jquery also has an instance method of the same name, get (), which gets the DOM element that matches the specified index in the current jquery object. )

jquery.post (URL [, data] [, success] [, type]) ( functions are used to obtain remote data through an AJAX request in the form of an HTTP POST .)

The Jquery.post () function is used to implement a simple post form of an AJAX request, which is implemented using Jquery.ajax () at the bottom, except that most of the infrequently used parameter settings are omitted and are limited to the HTTP POST method. Note that the function is loading data asynchronously )

Jquery.getjson (URL [, data] [, success]) ( a function is used to obtain remote JSON -encoded data through an AJAX request in the form of HTTP get .) JSON is a data format, JS native support JSON format, through the Jquery.getjson () from the server to obtain the JSON data, jquery will first try to convert it to the corresponding JS object. If the URL of the request includes "callback=?" And so on, jquery automatically sees it as a JSONP and executes the corresponding callback function to get the JSON data.

Important Note : The JSON data returned by the server must conform to strict json syntax, for example: all property names must be double-quoted , and all string values must be double-quoted ( Rather than single quotes). Note that the function is loading data asynchronously . )

jquery.getscript (URL [, success]) ( a function is used to load a JavaScript file in HTTP GET form and run it.) This function is used to dynamically load the JS file and execute the JS code in the file at the global scope. This function can load a cross-domain JS file. Note that the function is loading data asynchronously )

jQuery.fn.load (URL [, data] [, complete]) ( functions are used to load data from the server and Replace the contents of the current matching element with the returned HTML content.) the load () function uses the Get method by default, and if data is provided as an object , it is automatically converted to post. The load () function replaces only the internal contents (InnerHTML) of each matched element, so he defaults to DataType as html. You can also append the specified selector (separated from the URL) after the URL string to replace the contents of the current matching element with only part of the matching selector in the loaded HTML document. If the document does not match the contents of the selector, an empty string ("") is used to replace the contents of the current matching element.

If the current jquery object does not match any elements, the remote load request is not performed.

The load () described here is an AJAX request function, and jquery has an event function with the same name, load (), which executes the specified function when the document is loaded. The function belongs to the jQuery object (instance). The function is implemented at the bottom based on the function Jquery.ajax () .

Jquery.ajaxprefilter ([DataType,] handler) ( functions are used to specify callback functions that pre-process Ajax parameter options.) before all parameter options are processed by the jquery.ajax () function, you can use the callback function set by the function to pre-change any parameter options.

You can also specify the data type (DataType) to pre-process only the parameter options for the specified data type. The function can be called multiple times to allow for different callback functions to be specified for AJAX requests of different data types

DataType (optional/string type)

A string consisting of one or more data types separated by a space. If this parameter is not specified, all data types are represented. The available data types are "XML", "HTML", "text", "JSON", "JSONP", "script". The string is any combination of them (multiple types are separated by spaces), for example: "xml", "Text HTML", "script json Jsonp".

Handler (function type)

callback function for preprocessing parameter options. It has the following 3 parameters:

Options: (Object object) all the parameters of the current AJAX request option.

originaloptions: [Object Object] passed to $. Ajax () method with an unmodified parameter option.

jqxhr: The jqxhr object for the current request (XMLHttpRequest object in jquery encapsulation).

Jquery.ajaxsetup (settingsobj) ( The function is used to set The global default settings for AJAX.) This function is used to change the default settings option for AJAX requests in jquery. After all AJAX requests are executed, if the corresponding option parameters are not set, the changed default settings will be used. )

jQuery.fn.serialize ()(function is used to serialize a set of form elements and encode the contents of the form into a string for submission.) the serialize () function is commonly used to serialize the contents of a form for use in AJAX submissions.

The function is mainly based on the name and value of the valid form control used for submission , stitching them into a text string that can be directly used for form submission, which has been processed by standard URL encoding ( Character set encoding is UTF-8).

The function does not serialize form controls that do not need to be submitted, which is consistent with the regular form submission behavior. For example: a form control that is not in a <form> tag is not committed, a form control without a name attribute is not committed, a form control with the disabled property is not committed, and a form control that is not selected is not committed.

Unlike regular form submissions, a regular form typically submits a button control with name, and the serialize () function does not serialize a button control with name. )

JQuery.fn.serializeArray ()(function is used to serialize a set of form elements and encode the contents of the form into a JavaScript array.) often used to serialize the contents of a form into a JSON object for easy encoding into a JSON-formatted string.

The function encapsulates each form control that is available for submission as an object that has the name and Value property, the name of the form control, and the Value property. These object objects are then encapsulated as an array and returned.

The function does not serialize form controls that do not need to be submitted, which is consistent with the regular form submission behavior. For example: a form control that is not in a <form> tag is not committed, a form control without a name attribute is not committed, a form control with the disabled property is not committed, and a form control that is not selected is not committed.

Unlike regular form submissions, a regular form typically submits a button control with name, and the Serializearray () function does not serialize a button control with name. )

Jquery.param (obj [, traditional])(serializes a JS array or a purely object into a string value for use in a URL Query string or AJAX request. returns an empty string ("") if no array or "pure object" is passed in, or a direct error if the value of an unreachable property, such as null,undefined , is passed in.

The so-called "pure object" is an object created by itself through {} or new object () . JS built-in Boolean, number, String, Date, RegExp, Function, window and other types of objects are not considered "pure objects."

The returned string has been URL-encoded (with a character set of UTF-8))

JQuery.fn.ajaxStart (HANDLERFN) (for AJAX of the request Ajaxstart Event Binding handler function)

jQuery.fn.ajaxSend (HANDLERFN) (Set when AJAX the callback function to execute when the request is about to be sent. )

JQuery.fn.ajaxComplete (HANDLERFN) (Set when AJAX Request Complete ( whether successful or unsuccessful ) The callback function that is executed when the )

jQuery.fn.ajaxSuccess (HANDLERFN) (Set when AJAX the callback function to execute when the request completes successfully. )

jQuery.fn.ajaxError (HANDLERFN) (Set when AJAX the callback function to execute when the request fails. )

jQuery.fn.ajaxStop (HANDLERFN) (for AJAX of the request Ajaxstop The event binding handler function. )

  

So far, JQuery 1.9.1 version of the source analysis is complete. Welcome to make a shot of bricks.

If you feel this article is good, please click on the bottom right "recommended"!

jQuery-1.9.1 Source Analysis Series (16) ajax--response data processing and API grooming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.