Monday 13 August 2018

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!

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...