开发者

When to use .then, .done, .fail [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 10 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜