我正在执行 AJAX 调用(常规 JS),如果需要的时间超过 500 毫秒,我会显示“请稍候”框。
通常,如果我想立即放置密码框,我会这样做:
// show semi-transparent grey screen to block access to everything underneath
divGreyCoverAllNode.style.display = 'inline';
// show PW box. Prior to these lines, both coverall and PW were display=none
divPleaseWaitNode.style.display = 'inline';
// now do the AJAX and follow-up inside a zero timer; the timer is necessary to
// make the system pause to display the screen changes we previously invoked
setTimeout( function() {
// do my ajax call here, then after the call...
// take down the PW stuff
divPleaseWaitNode.style.display = 'none';
divGreyCoverAllNode.style.display = 'none';
},
0
);
就像我上面所说的,我想做的是仅当 AJAX 未在 500 毫秒内完成时才显示 PW。理想情况下,它会是这样的:
// set a timer to display PW in 500 milliseconds
myTimeEvent = setTimeout( function() {
divGreyCoverAllNode.style.display = 'inline';
divPleaseWaitNode.style.display = 'inline';
},
500
);
// do my ajax call here, then after the call...
clearTimeout(myTimeEvent);
// take down the PW stuff, in case it was displayed
divPleaseWaitNode.style.display = 'none';
divGreyCoverAllNode.style.display = 'none';
但是当 AJAX 花时间时,我似乎无法让系统暂停并显示 PW。我尝试过在零计时器中围绕 AJAX 和后续 block ,但没有解决。
有什么建议吗?
编辑: 重要事实:这不是异步ajax调用。这是一种不寻常的情况,需要一切等待 ajax 结果。
最佳答案
鉴于您正在进行同步 XHR 调用,您不能这样做。这就是同步的本质——一切都会停止,直到调用完成。当您使用同步 XHR 请求时,不仅 JavaScript 事件循环停止,而且实际上卡住了整个浏览器 UI(在 IE 和 Firefox < 3 中)。
也就是说,you're doing it wrong . 8.4%上个月报告的 IE9 挂起是由于同步 XHR 造成的。确实不存在“需要使用同步 XHR 请求的异常情况”这样的事情。提出您的请求,然后根据您在回调函数中获取的数据采取行动。
而不是类似:
// Do stuff, then when you need a request:
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send();
// Do more stuff
alert(xhr.responseText);
您需要:
// AJAX helper
function req(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) callback(xhr);
}
}
// Your code. Do stuff, then when you need an AJAX request:
req(url, function(xhr) {
// Do more stuff
alert(xhr.responseText);
});
显然这需要改进,但这说明了发出 AJAX 请求的正确方法。
关于javascript - 仅当ajax响应时间超过X毫秒时,如何调用 "Please Wait"窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7336382/