简体   繁体   中英

Jquery Ajax .done() behavior

I am wondering about the behavior of the code below. Ajax.chan(tid) is the ajax call found below. The other three functions are not Ajax related. When I don't pass a parameter to Display.channelLoad , the code works as expected and these functions run after the ajax is complete. But if I change that to .done(Display.channelLoad()) , this function runs before the ajax call is complete. This is probably some basic javascript knowledge that I am missing, but I would like to pass a parameter to Display.channelLoad and understand what is occurring here.

AjaxCall.chan(tid).done(List.articles)
                  .done(Display.channelLoad)
                  .done(Display.unblockUI);

AjaxCall.chan()

var AjaxCall = {
    chan: function(tid) {
        return getArticles = $.ajax({
            url: "http://ainonline.com/api/channel/" + tid,
            context: document.body,
            dataType: 'jsonp'
        });
    }

Thank you.

From the jQuery docs on .done :

The deferred.done() method accepts one or more arguments, all of which can be either a single function or an array of functions. When the Deferred is resolved, the doneCallbacks are called. Callbacks are executed in the order they were added. Since deferred.done() returns the deferred object, other methods of the deferred object can be chained to this one, including additional .done() methods. When the Deferred is resolved, doneCallbacks are executed using the arguments provided to the resolve or resolveWith method call in the order they were added. For more information, see the documentation for Deferred object.

What this means is that in your example the .done(List.articles) gets called with the result of $.ajax() . So it will get called with jqXHR object so it would look like this:

List.articles(data, textStatus, jqXHR)

And the same will happen for the other done calls in order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM