jquery Source Ajax Module Analysis

Source: Internet
Author: User
Tags script tag

Write in front:

Let's talk about the relevant functions in Ajax, and then combine the function functions to analyze the source code in detail.

Related functions:

>>ajax Global Event handlers

. Ajaxstart (Handler) Registers a Ajaxstart event handler. jquery triggers the Ajaxstart event when an AJAX request starts and there are no other outstanding Ajax requests at the same time .
. Ajaxsend (Handler) Registers a Ajaxsend event handler. The Ajaxsend event is triggered when an AJAX request is sent.
. Ajaxsuccess (Handler) Registers a ajaxsuccess event handler. The Ajaxsuccess event is triggered when an AJAX request succeeds.
. Ajaxerror (Handler) Registers a Ajaxerror event handler. The Ajaxerror event is triggered when an AJAX request is faulted.
. Ajaxcomplete (Handler) Registers a Ajaxcomplete event handler. The Ajaxcomplete event is triggered when an AJAX request completes.
. Ajaxstop (Handler) Registers a Ajaxstop event handler. Triggers the Ajaxstop event when an AJAX request is complete and there are no other incomplete AJAX requests at the same time .

Attention:

The processing functions of the six AJAX global events should be registered on the document.

For example: $ (document). Ajaxsuccess (handler);

Global in the AJAX options is the switch for the globally Ajax event. If the global option is set to False, none of the above Ajax global events will be triggered.

Particular attention is paid to the differences in the text described above in the Ajaxstart and Ajaxstop events.

>> basic functions of Ajax

Jquery.ajaxsetup ()

Jquery.ajaxsetup (options) sets the Ajax default options.

The Options object contains the Key/value key-value pairs used to configure the AJAX request.

The function extends directly to the Jquery.ajaxsetting object, which is the default configuration object for Ajax requests, and will have an impact on each subsequent AJAX request. The default option for extending AJAX is therefore not recommended for non-special cases.

The use of Ajax source code

// Extended jquery.ajaxsetting default Options collection Jquery.ajaxsetup ({    accepts: {        "text/javascript, Application/javascript, Application/ecmascript, Application/x-ecmascript "    },    contents: {        /(?: JAVA|ECMA) script/    },    converters : {        function(text) {            jquery.globaleval (text);             return text;}}    );

The above code extends the three default properties in Jquery.ajaxsetting, accepts, contents, converters, and three attribute objects that add support for the script data type. The purpose of these three options is described later.

Jquery.ajaxprefilter ()

Jquery.ajaxprefilter ([Datatypes,]handler)

Before each AJAX request begins, the request is processed in a pre-processing position.

Datatypes is a string that contains one or more spaces separated by datatype. The scope of the AJAX request used to qualify the predecessor processing application. The datatypes parameter is optional, and the default is "*", and when a datatype's predecessor handler queue finishes executing, the corresponding handler queue for "*" is executed.

The handler parameter function (OPTIONS,ORIGINALOPTIONS,JQXHR) is the specific processing function, Where the options parameter represents a collection of user options, that is, originaloptions and the default options collection, which is jquery.ajaxsetting synthesis, the final use of the option collection, Originaloptions represents a collection of user options when calling Ajax functions, JQXHR is Jquer The Y-encapsulated XHR object that contains the related properties and methods.

Chestnut: In the jquery source code, the Ajax module uses this function in two places.

//Handle Cache ' s special case and global//pre-processing of a script type request//A. Browser caching is not used by default//B. For cross-domain requests: Use the Get method, and set global to false, that is, do not trigger the globally Ajax object. Jquery.ajaxprefilter ("Script",function(s) {if(S.cache = = =undefined) {S.cache=false; }    if(s.crossdomain) {S.type= "GET"; S.global=false; }});//Detect, normalize options and install callbacks for JSONP requests//pre-processing of JSON and JSONP type AJAX requestsJquery.ajaxprefilter ("JSON Jsonp",function(S, originalsettings, jqxhr) {//omit other content ...    
    return "script";
}

Attention:

For a data type datatype, you can register multiple processing functions. The function is executed sequentially.

The handler function can return a datatype string, at which time jquery does not continue to execute other subsequent handlers in the queue, but instead adds the string to the datatypes header of the request option and executes the predecessor handler for the string instead.

For example, in the preceding code, in the pre-processing of JSON and JSONP, "script" is returned, then the script string is added to the Options.datatypes header (Options is the option set that the previously mentioned request is finally used) and jumps to the execution "Script" corresponds to the predecessor handler.

Jquery.ajaxtransport ()

Jquery.ajaxtransport (Datatype,handler)

DataType represents the requested data type.

The handler function, function (OPTIONS,ORIGINALOPTION,JQXHR), returns an object that represents the object that is actually used to complete the transport behavior when this data type is requested. I call it the Transfer object. The Transfer object should contain two methods, send and abort. Within jquery, this transport object is created for each AJAX request that corresponds to this data type.

The calling process is like this:

function (Options, Originaloptions, jqxhr) {  if/** * *  ) {      Return  {      function(headers, completecallback) {        //  Send code      },      function() {        //  Abort Code       }    };  }});

Where the parameters of the Send function

    • headersobject contains various settings for the request header
    • completeCallback 函数 当传输过程完成时,调用此函数来告诉Ajax传输过程结束。
    • completeCallback接受四个参数 ( status, statusText, responses, headers )
    • 其中responses是包含 dataType/value 的对象。例如像这样的{ xml: XMLData, text: textData }

This function provides great flexibility for AJAX requests, and you can customize your own transfer process. For example, you can customize an AJAX request that datatype as "image"

$.ajaxtransport ("image",function(s) {if(S.type = = = "GET" &&s.async) {varimage; return{send:function(_, callback) {image=NewImage (); functionDone (status) {if(image) {varStatusText = (Status = = = 200)? "Success": "Error", TMP=image; Image= Image.onreadystatechange = Image.onerror = Image.onload =NULL;          Callback (status, StatusText, {image:tmp}); }} Image.onreadystatechange= Image.onload =function() {Done (200 );        }; Image.onerror=function() {Done (404 );        }; IMAGE.SRC=S.url; }, Abort:function() {        if(image) {image= Image.onreadystatechange = Image.onerror = Image.onload =NULL;  }      }    }; }});

Notice the above callback (status, StatusText, {image:tmp}); The response parameter value of the callback function is {image:tmp}, and the image corresponds to the data type.

There are two calls to the Ajaxtransport function in jquery's Ajax module source code.

A transport object that is used to generate the default Ajax.

Jquery.ajaxtransport (function(s) {  
// Create a "*" corresponding to the transport, which handles all requests by default transport
Code omitted
});

The Ajaxtransport call above omits the datatype parameter, at which point the "*" corresponding transfer process is created, that is, the transfer process that is used by default.

In another case, Ajax uses a special transport object for requests for cross-domain "script" data types.

// Bind script tag hack transport // the transport object that the script file is requested to use.  function(s) {    // This transport only deals with cross domain requests    // handle only the cross-domain script data type
//You can see that the cross-domain script file is requested and executed through the HTML script tag.     if(s.crossdomain) {varscript, head= Document.head | | JQuery ("Head") [0] | |document.documentelement; return{send:function(_, callback) {script= document.createelement ("Script"); Script.async=true; if(s.scriptcharset) {Script.charset=S.scriptcharset; } script.src=S.url; //Attach handlers for all browsers                //The isabort parameter is set to True when the Script.onload function is manually called in the Abort method defined below                //the script element of IE supports the onreadystatechange event and the OnLoad event is not supported.                 //the script element of FF does not support the onReadyStateChange event, only the OnLoad event is supported. Script.onload = Script.onreadystatechange =function(_, Isabort) {//when Isabort, do clear script processing                    //The !script.readystate description is below FF, which indicates that load is complete                    ///loaded|complete/.test (script.readystate) indicates that the load is completed when ReadyState is required to be detected as loaded or complete under IE                    if(Isabort | |!script.readystate | |/loaded|complete/. Test (Script.readystate)) {                        //Handle memory leak in IEScript.onload = Script.onreadystatechange =NULL; //Remove the script                        if(Script.parentnode) {script.parentNode.removeChild (script); }                        //dereference the scriptScript =NULL; //Callback if not abort                        if( !Isabort) {Callback ("Success" );                }                    }                }; //circumvent IE6 bugs with base elements (#2709 and #4378) by prepending                //Use native DOM manipulation to avoid our dommanip AJAX trickeryhead.insertbefore (script, head.firstchild); }, Abort:function() {                if(script) {script.onload (Undefined,true );    }            }        }; }});

Attention:

Similar to the previous ajaxprefilter, each data type can define multiple transport functions. If one of the functions returns a Transfer object, the call to the function queue is terminated. If the specific data type does not receive the Transfer object, the corresponding transport function queue for "*" is called.

Jquery.ajax ()

Put it in a separate article.

>> Ajax-related shortcut methods

jquery.post ()
Jquery.get ()
Jquery.getjson ()
Jquery.getscript ()
. Load ()

Another piece of article to say.

>> Ajax source code architecture and Process analysis

Another piece of article to say.

>>ajax returns JQXHR object analysis, about deferred objects

Another piece of article to say.

Finally: The first write, write the article really trouble, feel the content of a good volume, womb write not finish, or a number of sections to write it. The source code of the Ajax module (with annotations) is posted directly first.

JQuery Source Ajax Module Analysis

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.