JQuery source code analysis series (31): Ajax deferred implementation

Source: Internet
Author: User

The underlying implementation of AJAX is provided by the browser. Therefore, any framework or library based on the api only refers to the process of making the optimal extension of ajax requests for the flexibility and compatibility and maintainability of functions: 1. Use new XMLHttpRequest or another form (IE) to generate the ajax object xhr. 2. Establish a connection in the form of xhr. open (type, url, async, username, password. 3. Use setRequestHeader to set the xhr request header ). 4. send data to the server. 5. Execute the onreadystatechange callback registered on xhr to process the returned data. In these steps, problems We developers may encounter: 1 cross-origin 2 json Format 3 dataType 4 AJAX garbled Problem 5 page cache 6 Status tracking 7 different platforms compatible with jQuery mainly to solve the problem above, then, based on this, the Ajax part of jQuery2.0.3 has more than 1200 Lines of source code, mainly for some extensions of ajax operations, it makes jQuery more flexible to rewrite the AJAX module in 1.5. It adds several new concepts. The AJAX module provides three new methods for managing and scaling AJAX requests. They are: pre-filter jQuery. ajaxPrefilter request distributor jQuery. ajaxTransport, type converter ajaxConvert. In addition, it overwrites the entire asynchronous queue processing and adds deferred to decouple the processing method completed by the task with the task itself and uses the deferreds object, multiple callback functions can be bound and executed when the task is completed. Bind these callback functions. These tasks can be asynchronous or synchronous. For example, 1. chain feedback done and fail copy code $. ajax ({url: "script. php ", type:" POST ", data: {id: menuId}, dataType:" html "}). done (function (msg) {$ ("# log" cmd.html (msg );}). fail (function (jqXHR, textStatus) {alert ("Request failed:" + textStatus) ;}); copy Code 2. separation of asynchronous and synchronous processing of replication code var aajax =$. ajax ({url: "script. php ", type:" POST ", data: {id: menuId}, dataType:" html "}). fail (function (jqXHR, textStatus) {alert ("Request failed: "+ TextStatus) ;}); // The synchronization is still executing the Code. This function may call dosomething () before AJAX ends. // the asynchronous function is still waiting for aajax to respond successfully. done (function (msg) {$ ("# log" cmd.html (msg) ;}) copying code is no longer limited to only one successful, failed, or completed callback function. On the contrary, these added callback functions are placed in an FIFO queue. 3. execute multiple ajax requests simultaneously to copy the code function ajax1 () {return detail .get('1.htm');} function ajax2 () {return detail .get('2.htm');} $. when (ajax1 (), ajax2 ()). then (function () {// success }). fail (function () {// Failed}); Copying code is more complicated. The principle is actually $. get returns a deferred object. Each AJAX method of jQuery contains a promise function to track asynchronous requests. The Return Value of the Promise function is a read-only view of the deferred object. Deferreds checks whether the current object has a promise () function to determine whether it can be observed. $. When () will wait for all AJAX requests to end, and then the call passes. then (),. the callback function registered by fail () (which callback functions are called depends on the end of the task ). These callback functions are executed in the order they are registered. The deferred object is the callback function solution of jQuery, which solves the problem of time-consuming operations, providing better control over those operations and a unified programming interface jqXHR object is nothing more than adding the deferred object in the ajax implementation logic, the entire ajax method is converted into a deferred object. In the ajax method, a jqXHR packaging object is returned, and all implementation methods ajax: function (url, options) are included in the object) {//......... return jqXHR} starts from jQuery 1.5, $. ajax () returns the XMLHttpRequest (jqXHR) object, which is a superset of the native XMLHttpRequest object of the browser. For example, it contains the responseText and responseXML attributes, and a getResponseHeader () method. When the transmission mechanism is not XMLHttpRequest (for example, when a JSONP request script returns a script tag), The jqXHR object tries its best to simulate the native XHR function. Since jQuery 1.5.1, The jqXHR object also contains the overrideMimeType method (which is valid in jQuery 1.4.x but is temporarily removed in jQuery 1.5 ).. The overrideMimeType () method may be used in the beforeSend () callback function. For example, modify the Content-Type header of the response: to unify the name of the callback function. ajax. JqXHR also provides the. error (). success () and. complete () methods. These methods all carry a parameter, which is a function, which is in the $. ajax () is called at the end of the request, and the parameters received by this function. the parameters for ajax () functions are the same. This will allow you to assign values to multiple callback functions in a single request, or even assign values to the callback function after the request has been completed (if the request has been completed, the callback function will be called immediately ). To be backward compatible with XMLHttpRequest, A jqXHR object will expose the following attributes and Methods: readyStatestatusstatusTextresponseXML and/or responseText when the underlying requests make XML and/or text responses respectively setRequestHeader (name, value) starting from the standard, replace the old value with the new value instead of the new value to the old value getAllResponseHeaders () getResponseHeader () abort () so before we mix in the jqXHR object of the package, we need to prepare the 1 asynchronous queue deferred 2 callback queue Callbacks to copy the code // Deferredsdeferred = jQuery. deferred (),/*** for all callback queues, no matter whether the added callback is triggered only once * @ type {[type]} */completeDeferr Ed = jQuery. callbacks ("once memory"), copy the code to add the attributes and methods of promise to jqXHR extension, and then add the complete method. Here the add method of the callback list is used (that is, add callback) deferred. promise (jqXHR ). complete = completeDeferred. add; image at this time, jqXHR has some features of promise and queues the callback with callback. Of course, there is a focus here. a read-only deferred object is returned. If a complete deferred object is returned, then, the external program can trigger the callback function of the deferred object at will. It is very likely that the callback function (resolve) is triggered before the end of the AJAX request ), this is contrary to the logic of AJAX. Therefore, to avoid accidental changes to the internal process of the task, we should only return the read-only deferred version of deferred. promise () and then change the corresponding done and fail to the alias success and error jqXHR. success = jqXHR. done; jqXHR. error = jqXHR. fail; we also need to register the user-defined internal callback function to the jqXHR object and copy the code // Add the callback queue for (I in {success: 1, error: 1, complete: 1}) {/*** register the callback function of the parameter to the internal jqXHR object, and call the callback function * register the callback function for the ajax object add * deferred to return the complete, error external capture */jqXHR [I] (s [I]);} copy the code jqXHR. success (s. success)-> jqXHR. done-> jQuery. callbacks ("once memory") jqXHR. error (s. error)-> jqXHR. fail-> jQuery. callbacks ("once memory") jqXHR. complete (s. complete)-> jQuery. callbacks ("once memory "). add (s. success)

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.