jquery Source Analysis Series: pre-filters and request-distributors in Ajax

Source: Internet
Author: User

After jQuery1.5, the Ajax module provides three new ways to manage and extend Ajax requests, respectively:

1. Pre-filter jQuery. Ajaxprefilter

2. Request Dispatcher JQuery. Ajaxtransport,

3. Type converter Ajaxconvert

SOURCE structure:

jquery.extend ({    /* * *     Pre-Filter     * @type {[type]}          */ Ajaxprefilter:addtoprefiltersortransports (prefilters),    /* * *     Request Dispatcher     * @type {[ Type]}     *    /ajaxtransport:addtoprefiltersortransports (transports),         ...........................});

It can be seen that these 2 methods are constructed by means of a private method addtoprefiltersortransports through curry, respectively, by maintaining a reference to prefilters and transports.

A simple mock-up of this structure

var prefilters = 2; var function (prefilters) {    returnfunction(b) {        return prefilters +  b;    }} var ajaxprefilter = addtoprefiltersortransports (prefilters) ajaxprefilter (//  3

Ajaxprefilter can be seen to maintain the addtoprefiltersortransports return function reference, this is the method of closure, which is also JS developers need to master

The benefit is merging multiple parameters, of course, because maintaining the reference cost is a little bit of performance consumption

Of course, jquery is not a simple type of pass-through, but it can also pass a reference-type callback function, so the closure component for the Ajaxprefilter method needs to be handled.

Populating the Prefilters processor

varPrefilters = {};varAddtoprefiltersortransports =function(structure) {return function(func) {structure[' * '] =func; }}varAjaxprefilter =addtoprefiltersortransports (prefilters) ajaxprefilter (function(options) {return{send:function() {}, callback:function(){        }    }})

In fact, that is, the corresponding method to make the function of the form to fill the prefilters or transports corresponding processing packaging object

Executes directly when it is used, and each function maintains its own reference

The benefits of this notation are naturally flexible, easy to maintain, and reduce the amount of code

And we often use jquery code very concise, such as merging the creation of multiple methods and so on

Jquery.each ([        "TabIndex",        "readOnly"        , "MaxLength"        , " Contenteditable "    function() {        jquery.propfix[this" ;    });

So the structure of the prefilters in this time is

Prefilters = {        function() {            return  {                function () {                },                function() {                }}}    }

Back to the point, so what is the role of introducing Ajaxprefilter and Ajaxtransport?

The pre-filter and the request dispatcher, when executed, traverse the internal variables prefilters and transports, which are initialized immediately after the jquery is loaded and populate the 2 objects from the closure method.

Ajaxprefilter and Ajaxtransport are all through Inspectprefiltersortransports Builder

The pre-filter in Prefilters is called before the request is sent and the request parameter is set, and the function inspectprefiltersortransports is called prefilters;

Cleverly, the request dispatcher in transports, after most of the parameters are set, also takes the function inspectprefiltersortransports to the request dispatcher that matches the request type:

functioninspectprefiltersortransports (structure, options, Originaloptions, jqxhr) {varinspected ={}, Seekingtransport= (Structure = = =transports); functionInspect (dataType) {varselected; Inspected[datatype]=true; Jquery.each (Structure[datatype]|| [],function(_, prefilterorfactory) {varDatatypeortransport =prefilterorfactory (Options, Originaloptions, JQXHR); if(typeofDatatypeortransport = = = "string" &&!seekingtransport &&!Inspected[datatypeortransport])                {Options.dataTypes.unshift (datatypeortransport);                Inspect (datatypeortransport); return false; } Else if(seekingtransport) {return! (selected =datatypeortransport);        }        }); returnselected; }    returnInspect (Options.datatypes[0]) | | !inspected["*" && Inspect ("*"));}

Traverse the Structure[datatype] array and execute the callback
Prefilterorfactory as a function array element
Executes the function if the returned result Datatypeortransport is a string and prefilters and has not been inspected
Add the string to the Options.datatypes array header
Continue recursive Datatypeortransport (when we use JSON/JSONP, we return "script", so we execute "script" related callbacks)
If it's transport, return the false results of Datatypeortransport.

Front Filter Prefilters

Simply speaking is a kind of hack practice, just say that the hack writing method is more brilliant than the event

We can see that the approach to prefilters is actually datatype for SCRIPT,JSON,JSONP.

When we dynamically load script files such as

$.ajax ({    type     "GET",    url      "test.js",    "script"});

So in the Inspectprefiltersortransports method Prefilters[script] can find the corresponding processing method, so it will execute

For example script hack, to force the special case and Crossdomain to handle the cache

Because the script's pre-filter is set, thescript does not necessarily mean cross-domain

Cross-domain is not disabled, mandatory type is get, no global time is triggered

function (s) {    if (s.cache = = = undefined        ) {false;    }     if (s.crossdomain) {        = "GET";    }});

So Prefilters is doing some of the necessary compatible processing for specific situations in a particular environment.

Request Dispatcher Transports

The request dispatcher sends the request as the name implies, so the underlying Ajax send request is via the Send method

Xhr.send ();

But jquery split the Send method and put the corresponding processing in the transports.

Then the transports object is also similar to the predecessor processor built by Jquery.ajaxtransport

such as the Script,send,abort method

Returns the Transports method

Transport = Inspectprefiltersortransports (transports, S, options, JQXHR);

If you think this article is helpful to you, please click "Recommend", would you like to make progress with me? Then "pay attention" to me!

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.