如何调用“请等待”只有当ajax的响应时间超过X毫秒时才使用

How to invoke a "Please Wait" window only if ajax takes more than X milliseconds to respond?

本文关键字:响应时间 ajax 调用 何调用 请等待 等待      更新时间:2023-09-26

我正在做一个AJAX调用(常规JS),如果它需要超过500毫秒,我想把我的"Please Wait"框

通常,如果我想立即放置PW盒子,我会这样做:

// 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和后续块在一个零定时器,但没有交易。

有什么建议吗?

编辑:重要事实:这是而不是一个异步ajax调用。这是一种不寻常的情况,要求所有内容都等待ajax结果。

考虑到您正在进行同步 XHR调用,您不能。这就是synchronous & & &;所有停止直到调用完成。当您使用同步XHR请求时,不仅JavaScript事件循环停止,实际上还冻结了整个浏览器UI(在IE和Firefox中)。3) .

也就是说,你做错了。上个月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请求的正确方法。

它不应该出现在ajax调用之后,它应该出现在回调函数中。AJAX请求与其他代码是异步的,您应该在请求的回调部分完成后执行您想要的操作。

看一下BlockUi。如果这看起来不适合您,您可以尝试使用

$(document).ajaxStop(DoSomething()); 

了解jQuery超时时间