【发布时间】:2015-05-12 16:45:17
【问题描述】:
我在一个包含在 setInterval 函数中的 .each 循环内有一个 ajax 调用。 这可以处理仪表板上的许多 div 的更新,只需 html 页面上的几行代码。
我担心服务器延迟与客户端速度。如果在循环进入下一次迭代之前服务器没有响应数据会发生什么?
那么,我的问题是,可以暂停循环直到成功执行吗?
Ajax 调用:
setInterval(function() {
$(".ajax_update").each(function(){
$.ajax({
type: "POST",
dataType: "json",
url: "ajax/automated_update/confirmed_appointments.php",
data: "clinic_id=<? echo $clinic_id ?>&tomorrow=<? echo $tomorrow ?>&"+$(this).data('stored'), // serializes the form's elements.
success: function(data)
{
$(data[0]).html(data[1]);
}
});
});
}, 5000); //5 seconds*
</script>
我已经研究了.ajaxComplete(),但我不知道如何将其应用为解决方案。
我还研究过将循环变成自称的东西,例如:
function doLoop() {
if (i >= options.length) {
return;
}
$.ajax({
success: function(data) {
i++;
doLoop();
}
});
}
但这不会干扰 .each 吗?我不明白这如何与 .each 和基于我的 div 类的循环一起发挥作用。
我就是想不通!任何帮助将不胜感激。
我能够在处理 ajax 调用时获得 .when,但我不明白如何让 .when 做我需要的事情(停止循环,直到 ajax 调用完成)。
$(".ajax_update").each(function(){
$.ajax({
type: "POST",
dataType: "json",
url: "ajax/automated_update/confirmed_appointments.php",
data: "clinic_id=<? echo $clinic_id ?>&tomorrow=<? echo $tomorrow ?>&"+$(this).data('stored'), // serializes the form's elements.
success: function(data)
{
$(data[0]).html(data[1]);
}
});
$.when( $.ajax() ).done(function() {
alert("Finished it");
});
});
【问题讨论】:
-
看看jquery ajax promise方法
-
谢谢你的链接。我在我的问题底部添加了代码 .when 在 .each 函数中,但我不明白如何制作 .when 做我需要的事情(停止循环直到ajax调用完成)。你能帮我理解从这里去哪里吗?