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!
Deferred() method in JQuery is a function which returns the utility object with methods which can register multiple callbacks to queues. It calls the callback queues, and relay the success or failure state of any synchronous or asynchronous function.
A deferred object is an object that can create a promise and change its state to resolved or rejected . Deferreds are typically used if you write your own function and want to provide a promise to the calling code. You are the producer of the value. A promise is, as the name says, a promise about future value.
The defer attribute is a boolean attribute. If the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing.
then() method in JQuery is used to add handlers which are to be called when the Deferred object is resolved, rejected, or in progress.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With