我有一个youtube频道名称数组:var a = ["MyHarto", "vlogbrothers", " pbsidechannel "];
我想遍历每个频道,查询Youtube Data API,并将每个频道的订阅者总数加起来。我的问题是,即使async设置为false的$。Ajax调用时,订阅者计数立即打印到屏幕上,而无需等待。下面是我的代码:
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调用成功并且订阅者计数最终被正确设置。
是否有一个干净的方法来阻止或做最后的刷新?我认为设置async为false会在这里工作。不幸的是,如果我在success函数中输出总数,屏幕在更新每个总数时就会闪烁一堆,这是我想避免的。
这是一个简单的例子,从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!" );
}
});