Can someone explain clearly how jQuery.when() and deferred.then() works?

I'm working on a web application and I need to load a few files $.ajax. I found something interesting in $.when().then().

It works great when I don't have anything special to do with the data returned by the request like this example:

$.when(
    $.getScript('js/script1.js'),
    $.getScript('js/script2.js')
).then(function(){
    // Do whatever I want once both scripts are loaded...
});

If works well when I have a single ajax request like this:

$.when(
    $.ajax('xml/myxml.xml')
).then(function(data){
    // Here I can work with data like I would with a regular ajax request
    alert($(data).find('mynode').text());
})

But if I try the following, I can't get it to work:

$.when(
    $.ajax('xml/myxml.xml'),
    $.getScript('js/script.js')
).then(function(data){
    // But here, I can't access $(data).find('mynode')...
})

I read the deferred object page but most of it was too technical for me and I'm unable to understand how I am supposed to be able to get my ajax data when I'm using $.when().then() to load scripts and data from multiple sources.

So if someone can help me find out how to use my ajax data in my test case above, it would be great! And if in the meantime someone can explain the deferred object thing in a manner that is easier to understand than the official jQuery documentation, it would be awesome!

Thank you!


Apparently, for each deferred object, at least if it is an Ajax request, $.when passes an argument like [ "success", statusText, jqXHR ] to the callback. jqXHR is an object representing the XMLHttpRequest (more about it in the $.ajax documentation). So the following should work:

$.when(
    $.ajax('xml/myxml.xml'),
    $.getScript('js/script.js')
).then(function(a){
    $(a[2].responseText).find('mynode');
});

See the first example in the $.when documentation.

Regarding deferred objects in general, maybe this question helps.

链接地址: http://www.djcxy.com/p/10330.html

上一篇: 避免在Django ORM中多次引用同一对象

下一篇: 有人可以清楚地解释jQuery.when()和deferred.then()的工作原理吗?