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

I am working on a web application and I need to upload several $ .ajax files. I found something interesting in $ .when (). Then ().

It works fine when I have nothing special about 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 it works well when I have one ajax request, for example:

 $.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 cannot 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 pending object page, but most of it was too technical for me, and I cannot figure out how I should be able to get my ajax when I use $ .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, that would be great! And if in the meantime someone can explain the pending object object in a way that is easier to understand than the official jQuery documentation, that would be awesome!

Thanks!

+7
source share
1 answer

Apparently, for each pending object, at least if it is an Ajax request, $.when passes an argument of type [ "success", statusText, jqXHR ] to the callback. jqXHR is an object representing XMLHttpRequest (more on this 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.

As for deferred objects in general, maybe this question helps.

+3
source

All Articles