2014-07-23 39 views
0

我有一个youtube通道名称数组: var a = [“MyHarto”,“vlogbrothers”,“pbsideachannel”];在多个Ajax调用完成后执行一个动作(设置async:false)

我想遍历每个频道,查询Youtube数据API,并将每个频道的订户总数加起来。我的问题是,即使在$ .ajax调用中将async设置为false,用户数量也会立即打印到屏幕上,而无需等待。这是我的代码:

var subscriberTotalCount = 0; 
function grabStatsChannel() { 
    $('#youtube-stats-ch').html("Working..."); 
    var myURL = "https://www.googleapis.com/youtube/v3/channels?"; 
    var a = ["MyHarto", "vlogbrothers", "pbsideachannel"]; 
    a.forEach(function(channel) { 
     var query_params = { 
      key : API_KEY, 
      forUsername : channel, 
      part : 'statistics' 
     }; 
     $.ajax(myURL, { 
      data : query_params, 
      type : 'GET', 
      async: false, 
      dataType : 'jsonp', 
      success : function(data) { 
       $.each(data.items, function(i, entry) {   
        subscriberTotalCount += parseInt(entry.statistics.subscriberCount); 
       }); 
      } 
     }); 
    }); 
    $('#youtube-stats-ch').html(''); 
    $('#youtube-stats-ch').append('Found' + subscriberTotalCount + ' subscribers.<br />'); 
} 

我试着设置一个ajaxcomplete函数,似乎从未被解雇。建议?我现在得到的是打印出0个订阅者,即使我可以看到记录了Ajax调用成功并且订阅者数量最终被正确设置。

有没有一种干净的方法来阻止或最终刷新?我认为将异步设置为false会在这里起作用。不幸的是,如果我在成功函数中打印总数,那么屏幕会随着每个总数更新而闪烁,这是我想避免的。

+0

您可以使用jQuery的递延方法,如'。当()'http://api.jquery.com/jQuery 。当/ – Klors

回答

1

下面是从jQuery的网站一个简单的例子来管理多个ajax调用... http://api.jquery.com/jquery.when/

$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2) { 
    // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively. 
    // Each argument is an array with the following structure: [ data, statusText, jqXHR ] 
    var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It" 
    if (/Whip It/.test(data)) { 
    alert("We got what we came for!"); 
    } 
}); 
+0

这真可爱!我只是试了一下,很好地链接在一起。谢谢。 – wck

相关问题