2011-06-29 194 views
1

我有超過100個Ajax請求,尤其取決於它在頁面上有多少個.miniCanvas類。我想發送下一個Ajax請求,因爲我收到了以前的Ajax響應。Ajax請求一步一步

這是我的代碼:

$def(".miniCanvas").each(
     function() 
     { 
      getChartData($def(this)); 
     }); 
    function getChartData(me) 
    { 
     $def.ajax(
     { 
      url: 'allmoves.php?path=getchart&'+me.attr('id'), 
      cache: false, 
      success:function(msg){handleChartData(msg, me)}, 
      error: function(msg){alert('Error loading data.')} 
     }); 
    } 
    function handleChartData(data, me) 
    { 
     var aData = new Array(); 
     id=me.children('div').attr('id'); 
     var plot1 = $def.jqplot (id, [JSON.parse(data)], 
     { 
      series:[{showMarker:false}], 
      axesDefaults: { 
       show: false, 
       showTicks:false 
      } 
     }); 
    } 

回答

3
var GetCharData = function() { 
    var queue = [], 
     running = false, 
     next = function() { 
      running = false; 
      if (queue.length) GetCharData(queue.shift()); 
     }; 

    return function(me) { 
     if (running) return queue.push(me); 
     running = true; 
     $.ajax({ 
      url: 'allmoves.php?path=getchart&'+me.attr('id'), 
      cache: false, 
      success: function(msg) { 
       // Handle Success 
      }, 
      error: function(msg) { 
       // Handle Failure 
      }, 
      complete: next 
     }); 
    }; 
}(); 

然後

$(".miniCanvas").each(function() { GetCharData($(this)); })

http://jsfiddle.net/robert/EHCW5/

1

你可以做這樣的事情:

http://jsfiddle.net/gx2yY/

基本上只是保持你每次遞增每次你得到一個AJAX的指標,結果,爲下一個元素調用AJAX。

注意:下面的代碼說明了這個想法,但不匹配你的代碼以便在jsfiddle中工作。

$(function(){ 
    var $ones=$(".one"); 
    var index=-1; 

    function doNext(){ 
     if(++index >= $ones.length) return; 

     var $this=$ones.eq(index); 

     $.ajax({ 
      url: '/echo/html/', 
      data: {delay: 1}, 
      cache: false, 
      success:function(msg){ 
       $this.text("DONE"); 
       doNext();  
      }, 
      error: function(msg){alert('Error loading data.')} 
     }); 
    } 

    doNext();  
});