JQuery-1.9.1 source code analysis series (16) ajax-ajax framework, jquery-1.9.1ajax

Source: Internet
Author: User

JQuery-1.9.1 source code analysis series (16) ajax-ajax framework, jquery-1.9.1ajax

I will not talk about ajax much more. Click here.

Since it is an ajax framework, let's talk about jQuery's ajax processing ideas.

Currently, all browsers support ajax, but different browsers may use different methods (IE uses new window. activeXObject ("Microsoft. XMLHTTP "), the standard browser uses new window. XMLHttpRequest ()). According to this idea, it seems that jQajax only needs to be compatible?

No, the native ajax has a disadvantage: it does not support cross-origin (same-origin strategy has been around for a long time, Baidu ). So how does jQajax solve cross-origin problems?

The path of the image is not a domain with your server. You can try to see that all the labels with the src attribute are not affected by the same-source policy. Therefore, jQuery uses this attribute. For cross-origin requests, the src of the script label is used to request the path.

Then jQuery adds three listening methods for ajax events:

1. Global events: $ (document). on ('ajaxstart', func );

2. ajax callback settings: $. ajax ({url: "php.html", complete: func });

3. deferred binding method: $. ajax (...). Done (func );

Basically, this is what jQajax does.

 

Before entering the core of the ajax framework, we will analyze several serialized submission form functions prepared by jQuery.

A. Form serialization

The so-called form serialization refers to the composition of the content to be submitted by the form, similar to: "key = value & key = value ..." String.

Serialization uses three functions:

JQuery. fn. serialize ()(The serialization function filters out the data to be submitted in the form and returns the data in serialized string format, for example, "key = value & key = value ...")

JQuery. fn. serializeArray ()(Filter out the data to be submitted in the form and return it in the format of an array of objects with key/value pairs, and return [{name: 'key', value: 'select1 '}, {name: 'selecttm', value: 'selectm1 '}, {name: 'selecttm', value: 'selectm2'}, {name: 'key2', value: 0}…])

JQuery. param (serializeArray, traditional)(Serialize the object array of key/value pairs to "key = value & key = value ..." String ).

  

Serialize directly calls jQuery. param (this. serializeArray.

The source code of serializeArray is as follows::Perform the following three steps:Extract form elements, filter out form elements that meet the submission conditions, and combine them into an array of objects for key/value pairs.

SerializeArray: function () {// obtain the elements related to the form in form to form the array return this. map (function () {// The form node has the feature var elements = jQuery. prop (this, "elements"); return elements? JQuery. makeArray (elements): this ;}) // filter out the elements of the form to be submitted (including the name, non-disabled, non-submit button, and checkbox/radio checked elements ). filter (function () {var type = this. type; // use. is (": disabled") filters out unavailable form elements return this. name &&! JQuery (this). is (": disabled") & rsubmittable. test (this. nodeName )&&! RsubmitterTypes. test (type) & (this. checked |! Manipulation_rcheckableType.test (type);}) // forms the submission element to form an array of objects named and value. map (function (I, elem) {var val = jQuery (this ). val (); return val = null? Null: jQuery. isArray (val )? JQuery. map (val, function (val) {return {name: elem. name, value: val. replace (rCRLF, "\ r \ n") };}: {name: elem. name, value: val. replace (rCRLF, "\ r \ n ")};}). get ();}

It should be noted that jQuery's filtering result conforms to the normal form submission result: // filter out the elements of the form to be submitted (including the name, non-disabled, non-submit button, and checkbox/radio checked elements)

 

The source code of the param function is as follows:Mainly for two processes:Encode the key/value as the URI component (ensure that the key and value do not contain special symbols, that is, ensure the correctness of the "=" segmentation), use the "&" link and replace the blank space with "+"

JQuery. param = function (a, traditional) {var prefix, s = [], add = function (key, value) {// If value is a function, run the command to get the true value = jQuery. isFunction (value )? Value (): (value = null? "": Value); // the key and value are encoded as URI components to ensure that the key and value do not contain special symbols, that is, the correctness of the "=" split s [s. length] = encodeURIComponent (key) + "=" + encodeURIComponent (value );};... // input an array. Suppose it is a form key-Value Pair array if (jQuery. isArray (a) | (. jquery &&! JQuery. isPlainObject (a) {// serialize the form Element jQuery. each (a, function () {add (this. name, this. value) ;}) ;}else {...} // return the serialization result. Note: The blank space is replaced with "+" return s. join ("&"). replace (r20, "+ ");};

Click encodeURIComponent to view details.

 

B. ajax event listening

There are three ways to bind events to ajax:

1. Global events: $ (document). on ('ajaxstart', func );

2. ajax callback settings: $. ajax ({url: "php.html", complete: func });

3. deferred binding method: $. ajax (...). Done (func );

Next we will explain their implementation one by one.

 

Global events (ajaxStart/ajaxStop/ajaxComplete/ajaxError/ajaxSuccess/ajaxSend)

  Using the. on event binding method, we can undoubtedly bind ajax listening events. In addition, we can directly use $ (...). AjaxStart (func) to bind events. Their implementation is also bound with. on.

jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){        jQuery.fn[ type ] = function( fn ){            return this.on( type, fn );        };});

It is relatively simple to trigger events. jQuery. event. trigger is directly triggered at the right time during ajax processing. Take ajaxStart as an Example

// If no request is being executed at this time, the ajaxStart event if (fireGlobals & jQuery. active ++ === 0) {jQuery. event. trigger ("ajaxStart ");}

  

Ajax callback settings (beforeSend/complete/success/error)

  There are two types of callback items for triggering setting: beforeSend can be called directly at the appropriate time. Source code

// Call the beforeSend callback. if the callback fails or abort is returned, if (s. beforeSend & (s. beforeSend. call (callbackContext, jqXHR, s) = false | state = 2) {// abort if return jqXHR is not ready. abort ();}

Complete/success/error uses the Deferred feature to add the callback to the delayed queue, waiting for processing of the delayed status. Source code

// Create the final option object s = jQuery. ajaxSetup ({}, options )... deferred = jQuery. deferred (), completeDeferred = jQuery. callbacks ("once memory "),... // Add the latency event deferred. promise (jqXHR ).Complete= CompleteDeferred. add; jqXHR.Success= JqXHR. done; jqXHR.Error= JqXHR. fail; // install callback to deferreds for (I in {Success: 1,Error: 1,Complete: 1}) {jqXHR [I] (s [I]);} // execute the completeDeferred latency list function done (){... // execute Complete processingCompleteDeferred. fireWith(CallbackContext, [jqXHR, statusText]);...}

 

Deferred binding callback

  Not to mention binding events in the Deferred mode, because ajax itself is a delayed object. Use $. ajax (…) directly (...). Done (fn). fail (fn). progress (fn). always (fn). then (fn ). Source code

deferred = jQuery.Deferred(),completeDeferred = jQuery.Callbacks("once memory"),...deferred.promise( jqXHR ).complete = completeDeferred.add;...return jqXHR;

 

If you think this article is good, click [recommendation] in the lower right corner ]!

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.