Reference http://www.ruanyifeng.com/blog/2011/08/a_detailed_explanation_of_jquery_deferred_object.html
The Ajax method has been rewritten since the jQuery1.5 version, not the same as it used to be. Now $.ajax () will return a Promise/deffered object
This object has the Do () fail () always () and then () Promise () reject () methods
I used to write Ajax like this,
$.ajax ({
URL: "Test.html",
Success:function () {
Alert ("Haha, success!") ");
},
Error:function () {
Alert ("Error! ");
}
});
Now it is
$.ajax ({
URL: '/path/to/file ',
Type: ' Default GET (other Values:post) ',
DataType: ' Default:intelligent Guess (other values:xml, JSON, script, or HTML) ',
Data: {param1: ' value1 '},
}). Done (function () {
Console.log ("Success");
}). Fail (function () {
Console.log ("error");
}). Always (function () {
Console.log ("complete");
});
Obviously, done () is equivalent to success () fail () is the error ()
Or
$.ajax ({
URL: ' Test1.json ',
DataType: ' Text ',
}). Then (function (res) {
Alert (' Wahha ');
Console.log (RES);
});
You can use the same callback for different requests
$.when ($.ajax ({
URL: ' Test1.json ',
DataType: ' Text ',
}), $.ajax ({
URL: ' Test2.json ',
DataType: ' Text ',
}). Done (function (res) {
Alert (' Wahha both ');
Console.log (res);//response of the first AJAX request
})
Add a callback function for a normal function
This is the most recommended way
var wait = function (DTD) {
var DTD = $. Deferred (); Inside the function, create a new deferred object
var tasks = function () {
Alert ("Execution finished!") ");
Dtd.resolve (); Change the execution state of the deferred object resolve to resolve
};
SetTimeout (tasks,5000);
return Dtd.promise (); Returns the Promise Object
};
$.when (Wait ())
. Done (function () {alert ("Haha, success! "); })
. Fail (function () {alert ("Error! "); });
The source post was previously a $. Deferred () as a global object, but that can change the state of execution in the global.
So he used the deferred.promise ()
The last thing I did was to put deferred in the function and solve the problem.
So later, multiple nested AJAX requests can be written like this
var Promisea = $.get (Urla);
Promisea.always (Donefna, Failfna, Progressfna);
var promiseb = Promisea.then (function () {
Return $.get (URLB);
});
Promiseb.always (DONEFNB, FAILFNB, PROGRESSFNB);
The Promise in jquery