When to use .then, .done, .fail [closed]
If I limit myself to the .ajax method (and NOT to the shortcuts like .get and .load), t开发者_如何学编程hen should I use the deferred object methods
.then, .done, .fail, .when, .reject, .resolve, .always, .promise
or the Global Event Handlers:
.ajaxSuccess, .ajaxComplete, .ajaxError, .ajaxSetup, .ajaxStart, .ajaxStop,
Methods on a deferred objects (such as can be constructed from a jQuery AJAX request) are executed in relation to that particular deferred. This is quite different from global event handlers, as these will called when ANY AJAX requests. So you will see the same results if you only have one AJAX request on each page, but things will of course be quite different with multiple AJAX requests.
The closer counterpart to the deferred object methods are the error
, success
, and complete
methods which define callbacks for a jQuery AJAX request.
Example
var jqxhr = $.ajax({url:'myapi.json', method:'post'});
Now, with jqxhr
, $.when(jqxhr).then(…)
is equivalent to jqxhr.complete(…)
. A similar relationship applies to resolve
and success
, also reject
and error
.
Basically if you wanted to use the deferred method you'd assign your AJAX request to a variable.
var request = $.ajax({ /* Make ajax goodness */ });
Then you can reference this using the deferred object.
$.when( request ).then(function() {
// Success
});
But to my knowledge they are the same...I'll check the docs and update if I'm incorrect.
精彩评论