JQuery queue and dequeue
I have multiple jquery ajax calls that are somewhat interdependent. Both are fired on page load at different times (with getData
being called before showData
and showData
is dependent on getData
being called first).
On some clients, the showData
runs first before getData
.
How do I recreate this error as we don't see that happening everywhere. It appears that this depends on the load on the server b开发者_如何学Pythonut we are unable to confirm that.
To fix it, I understand I can use Jquery's
queue
anddequeue
. However, in certian scenarios, I need to run this outside of the queueing infrastructure. For example, mygetData
looks like this:function getData() { $.ajax(//options) } function showData() { $.ajax(//options) }
Sometimes, I need both of them to be executed (with getData
being called first), but in certain scenarios, they are independent of each other with getData
being called without ever calling showData
.
If I queue them up, can I still call them independently?
I think you should use the Deferred object types available in jQuery 1.5+ rather than a queue:
function getData() {
return $.ajax(...);
}
function showData() {
return $.ajax(...);
}
var gd = getData();
if (showDataNeeded) {
// only call showData() when getData() has finished
gd.done(showData);
}
Why not just attach showData
to getData
's on success callback like this:
function getData(){
$.ajax({
url: "/your.url",
success: showData
});
}
function showData(){
// foo bar here
}
This also deals with the fact that you might not want to call showData
unless getData
succeeds.
精彩评论