另一种解决方案,使用递归:
$.fn.loadYoutubeResource = function(resource_request, resource_type, resource_id, resource_container, pageToken = null, callback = null){
$.ajax({
url: "https://www.googleapis.com/youtube/v3/" + resource_request,
type: 'get',
dataType: 'json',
data: {
part : 'snippet',
[resource_type]: resource_id,
maxResults : 50,
pageToken: pageToken,
key: '< API Key >',
},
success: function(data) {
console.log("New resource " + resource_type + " loaded:");
console.log(data);
for(var index = 0; index < data.items.length; index++){
var url = data.items[index]['snippet'].thumbnails.default.url;
var ytb_id = data.items[index]['id'];
jQuery('#' + resource_container).append('<img class="tube_thumbs" src="' + url + '" id="' + ytb_id
+ '" title="' + data.items[index]['snippet']['title'] + '" >');
}
if ( data.nextPageToken == null)
return callback();
$.fn.loadYoutubeResource(resource_request, resource_type, resource_id, resource_container, data.nextPageToken, callback);
}
});
}
然后调用如下:
jQuery('body').append('<div id="ytb_container"></div>');
$.fn.loadYoutubeResource('playlistItems', 'playlistId', 'PLmwK57OwOvYVdedKc_vPPfbcsey_R0K8r', 'ytb_container', null, function(){ <callback code>});