我有4个不同的JQuery AJAX函数,每个函数都从last.fm API中获取不同的信息。此信息必须在工具提示中连接在一起。
这是我的4个功能:
var getTrackAlbum = function(track, artist) {
$.getJSON(
settings.PHP_REQUEST_URL,
{
method: "track.getInfo",
api_key : settings.LASTFM_APIKEY,
track : track,
artist : artist,
format : "json"
},
function(data) {
return data.track.album.title;
});
}
var getArtistImage = function(artist) {
var options = {
artSize: 'medium',
noart: 'images/noartwork.gif',
}
if(options.artSize == 'small'){imgSize = 0}
if(options.artSize == 'medium'){imgSize = 1}
if(options.artSize == 'large'){imgSize = 2}
$.getJSON(
settings.PHP_REQUEST_URL,
{
method: "artist.getInfo",
api_key : settings.LASTFM_APIKEY,
artist : artist,
format : "json"
},
function(data) {
return stripslashes(data.artist.image[imgSize]['#text']);
});
}
var getArtistTopAlbums = function(artist) {
var albums = new Array();
var onComplete = function() {
return albums;
}
$.getJSON(
settings.PHP_REQUEST_URL,
{
method: "artist.getTopAlbums",
api_key : settings.LASTFM_APIKEY,
artist : artist,
format : "json"
},
function(data) {
$.each(data.topalbums.album, function(i, item){
albums[i] = item.name;
if(i == 2) {
onComplete.call(this);
return;
}
});
});
}
var getArtistTopTrack = function(artist) {
$.getJSON(
settings.PHP_REQUEST_URL,
{
method: "artist.getTopTracks",
api_key : settings.LASTFM_APIKEY,
artist : artist,
format : "json"
},
function(data) {
return data.toptracks.track[0].name;
});
}
我决定不在一个独特方法中执行所有请求以便重用。但是,现在我想在设置工具提示的HTML之前等待所有AJAX请求完成。
以下是我的工具提示的代码:
$('.lfm_info').on('mouseover', function(){
var toolTip = $(this).children('.tooltip');
var trackhtml = $(this).parent().children('.lfm_song').html().split(".");
var track = trackhtml[1].trim();
var artist = $(this).parent().children('.lfm_artist').html();
// needs to wait until the AJAX is done!
toolTip.html('html here');
$('#tracks').mouseleave(function(){
if(toolTip.is(':visible')){
toolTip.fadeOut(500);
};
});
toolTip.fadeIn(500);
});
}
在调用toolTip.html(...)
之前,我如何等待所有请求完成?
答案 0 :(得分:13)
存储每个请求,然后使用$.when
创建一个延迟对象来监听它们全部完成。
var req1 = $.ajax({...});
var req2 = $.ajax({...});
var req3 = $.ajax({...});
$.when( req1, req2, req3 ).done(function(){
console.log("all done")
});