Jarson jquery's Deferred object usage--Implement AJAX linear request data

Source: Internet
Author: User

The problem with a recent AJAX request data is that you want to request 3 different interfaces and then manipulate the data after the request is complete, the main problem is not knowing which of the 3 requests will come back first, or when the operation is not guaranteed that the data has been returned, The first thing that can be done is to write the second Ajax request in the succes of the first Ajax request, but we all know that this writing will be very inefficient and low, so give up.

Consulted for a long time, finally found a way. Use the deferred object.

The development of jquery is fast, with a small version of almost every half-yearly, every two months. Each version introduces some new features. What I want to introduce today is a new feature introduced from the jquery 1.5.0 Release----Deferred object.

First, what is the deferred object?

simply put, the deferred object is the callback function solution for jquery. in English, defer means "delay", so the meaning of the deferred object is "delay" to some point in the future to execute. It solves the problem of how to handle time-consuming operations, provides better control over those operations, and a unified programming interface.

Ii. General Wording

The Ajax operation of jquery is traditionally written like this:

$.ajax ({

URL: "Test.html",

Success:function () {
Alert ("Haha, success!") ");
},

Error:function () {
Alert ("Error! ");
}

});

After the $.ajax () operation is complete, if you are using a jquery that is less than 1.5.0, you are returning the XHR object, you cannot do the chained operation, and if you are above the 1.5.0 version, the deferred object is returned, and you can chain-operate.

Iii. the new wording

$.ajax ("test.html")

. Done (function () {alert ("Haha, success! "); })

. Fail (function () {alert ("Error! "); });

As you can see, done () is equivalent to the success method, and Fail () is equivalent to the error method. After using chained notation, the readability of the code is greatly improved.

Iv. specifying multiple callback functions for the same operation

One of the great benefits of deferred objects is that it allows you to freely add multiple callback functions.

As an example of the above code, if the Ajax operation succeeds, in addition to the original callback function, I would like to run a callback function, how to do?

It's very simple, just add it to the back of the line.

 $.ajax ("test.html")

. Done (function () {alert ("Haha, success! ");} )

. Fail (function () {alert ("Error! "); } )

  . Done (function () {alert ("Second callback function!) ");} );

The callback function can add any number of them, which are executed in the order in which they are added.

Five, the next is to solve the problem of the landlord point. Specifying callback functions for multiple operations

Another great benefit of the deferred object is that it allows you to specify a callback function for multiple events, which is not done in traditional notation.

  $.when ($.ajax ("test1.html"), $.ajax ("test2.html"))

. Done (function () {alert ("Haha, success! "); })

. Fail (function () {alert ("Error! "); });

This code means that you perform two operations $.ajax ("test1.html") and $.ajax ("test2.html"), and if successful, run the callback function specified by done (), and if one fails or fails, execute the callback function specified by fail (). And the above test1.html and test2.html are requested at the same time. So the effect of linear request data is realized.

Vi. Complete examples of deferred

The biggest advantage of the deferred object is that it extends this set of callback function interfaces from Ajax operations to all operations. That is, any operation----whether it is an AJAX operation or a local operation, whether it is an asynchronous operation or a synchronous operation----can use various methods of the deferred object to specify a callback function.

 var DTD = $. Deferred (); Create a new Deferred object

var wait = function (DTD) {

var tasks = function () {

Alert ("Execution finished!") ");

      dtd.resolve (); change the execution status of the deferred object "completed" to execute the Done function immediately

};

SetTimeout (tasks,5000);

    return dtd.promise ();// cannot return DTD directly, must return Dtd.promise ();

};

  

 $.when (Wait (DTD))

. Done (function () {alert ("Haha, success! "); })

. Fail (function () {alert ("Error! "); });

Vii. points needing attention

1, $.when () parameter can only be deferred object, so you need to create an object first

2, $.when () The default execution status of "completed", immediately trigger the subsequent done () method, which loses the function of the callback function. The purpose of dtd.promise () is to ensure that the current execution state is not changed by the user itself.

3, finally do not forget, after modifying wait, the call must be passed directly to the DTD parameter (deferred object);

Viii. Summary: The method of deferred object, interested to see

There are several ways to deferred objects, and here's a summary:

(1)$. Deferred () generates a Deferred object.

(2)Deferred.done () Specifies the callback function when the operation succeeds

(3) Deferred.fail () specifies the callback function when the operation fails

(4) Deferred.promise () when there are no parameters, the function is to keep the running state of the deferred object unchanged; When the parameter is accepted, the role is to deploy the deferred interface on the Parameter object.

(5) Deferred.resolve () manually changes the running state of the deferred object to "completed", triggering the Done () method immediately.

(6) $.when () specifies a callback function for multiple operations.

In addition to these methods, the deferred object has three important methods that are not covered in the tutorial above.

(7) Deferred.then ()

Sometimes to save time, you can write the done () and fail () together, and this is the then () method.

$.when ($.ajax ("/main.php"))

  . Then (Successfunc, Failurefunc);

If then () has two parameters, then the first parameter is the callback function of the Done () method, and the second parameter is the callback method of the Fail () method. If then () has only one parameter, then it is equivalent to done ().

(8) Deferred.reject ()

This method, in contrast to Deferred.resolve (), triggers the Fail () method immediately after the call changes the running state of the deferred object to "failed".

(9) Deferred.always ()

This method is also used to specify the callback function, which is the function, regardless of whether the call is Deferred.resolve () or Deferred.reject (), and finally always executed.

$.ajax ("test.html")

. Always (function () {alert ("Executed! ");} );

Jarson jquery's Deferred object usage--Implement AJAX linear request data

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.