好吧,我很欣赏Javascript不是C#或PHP,但我总是回到Javascript的一个问题上--不是JS本身,而是我对它的使用。
我有一个函数:
function updateStatuses(){
showLoader() //show the 'loader.gif' in the UI
updateStatus('cron1'); //performs an ajax request to get the status of something
updateStatus('cron2');
updateStatus('cron3');
updateStatus('cronEmail');
updateStatus('cronHourly');
updateStatus('cronDaily');
hideLoader(); //hide the 'loader.gif' in the UI
}
问题是,由于Javascript在代码中跃进的强烈愿望,加载器永远不会出现,因为'hideLoader‘函数紧随其后运行。
我该如何解决这个问题呢?或者换句话说,我如何才能让javascript函数按照我在页面上编写的顺序执行……
发布于 2010-04-14 21:22:27
出现这个问题是因为AJAX本质上是异步的。这意味着updateStatus()
调用确实是按顺序执行的,但会立即返回,并且JS解释器在从AJAX请求检索任何数据之前到达hideLoader()
。
您应该在AJAX调用完成的事件上执行hideLoader()
。
发布于 2011-07-14 20:35:42
我认为你所需要做的就是在你的代码中包含以下内容:
async: false,
因此,您的Ajax调用将如下所示:
jQuery.ajax({
type: "GET",
url: "something.html for example",
dataType: "html",
async: false,
context: document.body,
success: function(response){
//do stuff here
},
error: function() {
alert("Sorry, The requested property could not be found.");
}
});
显然,需要对XML
、JSON
等进行一些更改,但async: false,
是这里的主要内容,它告诉JS引擎等待成功的调用返回(或失败),然后继续执行。记住,这有一个缺点,那就是在ajax返回之前,整个页面都会变得没有响应!通常在毫秒内,这不是一个大的交易,但可能需要更长的时间。
希望这是正确的答案,它对您有帮助:)
发布于 2010-04-14 21:34:59
我们在我们的一个项目中有类似的东西,我们通过使用计数器解决了它。如果您在AJAX请求的响应函数中为每个updateStatus
调用增加计数器并减少它(取决于您正在使用的AJAX JavaScript库)。
一旦计数器达到零,所有AJAX请求都完成,您就可以调用hideLoader()
了。
下面是一个示例:
var loadCounter = 0;
function updateStatuses(){
updateStatus('cron1'); //performs an ajax request to get the status of something
updateStatus('cron2');
updateStatus('cron3');
updateStatus('cronEmail');
updateStatus('cronHourly');
updateStatus('cronDaily');
}
function updateStatus(what) {
loadCounter++;
//perform your AJAX call and set the response method to updateStatusCompleted()
}
function updateStatusCompleted() {
loadCounter--;
if (loadCounter <= 0)
hideLoader(); //hide the 'loader.gif' in the UI
}
https://stackoverflow.com/questions/2637626
复制相似问题