开发者

JQuery queue and dequeue

开发者 https://www.devze.com 2023-03-15 16:57 出处:网络
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

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.

  1. 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.

  2. To fix it, I understand I can use Jquery's queue and dequeue. However, in certian scenarios, I need to run this outside of the queueing infrastructure. For example, my getData 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消