【发布时间】:2014-01-08 19:35:26
【问题描述】:
我正在制作多个 JSON GET 直到满足一个条件。下面代码的问题是函数tuneTileLoadedFunction()在条件满足之前被调用(在最终的GET请求之前)。我只想在最终加载完成后调用该函数。
我该怎么做?与http://api.jquery.com/jquery.when/ 有关吗?我看过这个,但无法理解我已经完成的事情。
当我将tuneTileLoadedFunction() 替换为 //whatever 它不调用函数时(我猜是因为数据尚未加载)。
谢谢:)
checkIfTuneTileLoaded();
function checkIfTuneTileLoaded() {
var tuneTileLoaded = $("a[href*='" + location.pathname + "']").length;
alert(tuneTileLoaded);
if (tuneTileLoaded == 1) {
//whatever
} else {
alert('tuneTileNotPresent');
tumblrPostsRetrieved += 20;
$.ajax({
type: 'GET',
url: 'http://api.tumblr.com/v2/blog/onrepeatthisweek.tumblr.com/posts?api_key=cCaCiEE6kd5pInej2YFU0xdC4msLOE3R3IhYXcR1W6Irza8sJq&tag=overandoverandoverandover&offset=' + tumblrPostsRetrieved,
data: { get_param: 'value' },
dataType: 'jsonp',
success: function (data) {
for (i = 0; i <= 19; i++) {
$('#recent-posts').append('<li><a href="' + data.response.posts[i].post_url +'"> ' + data.response.posts[i].title + '</li>');
}
maxScrollLeft = document.getElementById("tunesID").scrollWidth - document.getElementById("tunesID").clientWidth;
checkIfTuneTileLoaded();
tuneTileLoadedFunction();
alert('success');
}
});
}
}
更新/解决:
我没有解决我试图解决的问题(监听带有 Ajax 请求的递归函数的结尾)。对我来说,解决方案不是等待每个请求完成,而是在呈现每个项目时检查它们是否符合我的要求:
for (i = 0; i <= 19; i++) {
$('#recent-posts').append('<li><a href="' + data.response.posts[i].post_url +'"> ' + data.response.posts[i].title + '</li>');
if (data.response.posts[i].post_url == window.location) {
tuneTileLoaded = 1;
tuneTileLoadedFunction();
}
}
【问题讨论】:
-
tuneTileLoadedFunction();似乎是在第二次 GET 请求之后调用的,我以为它会在第一次之后调用。至关重要的是,它在第三个也是最后一个之前。你可以在这里看到这个:onrepeatthisweek.tumblr.com/post/38909622396/… -
好吧,你肯定不想在它所在的地方调用它。相反,您希望 checkIfTuneLoaded 有一个在 ajax 调用完成时执行的回调,以便您可以在那时执行 tuneTileLoadedFunction。
-
是的,我理解你的逻辑,我只是没有实现它的知识。我不知道如何监听所有正在完成的 GET 请求。
-
您不需要全部收听,只需收听最后一个,因为您一次只发送 1 个。
-
这样看。这是一个递归函数。当它停止递归时,你就知道它已经完成了。