发送 ajax 请求和接收响应(同步)
Sending ajax request and receiving response (synchronised)
我正在发送 ajax 请求并在我的 js/html 应用程序中处理响应。该设备是 Windows Mobile CE,没有 jquery 支持并且设备浏览器 (IE) 不支持事件处理程序,因此我无法使用异步调用。无论如何,我的问题是,在发送事件之前,我想显示一条 请稍候消息,在收到响应后我想再次隐藏它。
function sendRequest() {
// make please wait visible
document.getElementById("pleasewait").style.display = "block";
console.log("pleasewait visible.");
var XHR = new XMLHttpRequest();
// synch call
XHR.send(sendData);
// suppose it takes 20-30 seconds
console.log("response received :" + XHR.responseText);
XHR.open('POST', 'url', false);
// make please wait hidden
document.getElementById("pleasewait").style.display = "none";
}
但是,当我 运行 它时,pleasewait 元素在我们收到响应(不是在发送之前)时可见,并且即使该过程需要 20-30 秒也会立即再次隐藏。控制台消息以正确的顺序显示,但请稍候元素未正确更新。我尝试了一些 setTimeouts 但没有期望的结果。我无法添加一些 jsfiddle,因为很难在远程上实现 ajax 请求处理程序。
Browsers will freeze when doing synchronous ajax request hence the synchronous
request prevents the display re-flow!
我建议的唯一解决方案是使用 setTimeout
,持续时间 0
!
function sendRequest() {
document.getElementById("pleasewait").style.display = "block";
setTimeout(function() {
var XHR = new XMLHttpRequest();
XHR.send(sendData);
console.log("response received :" + XHR.responseText);
XHR.open('POST', 'url', false);
document.getElementById("pleasewait").style.display = "none";
}, 0);
}
注: Here是一些相关资料!
我正在发送 ajax 请求并在我的 js/html 应用程序中处理响应。该设备是 Windows Mobile CE,没有 jquery 支持并且设备浏览器 (IE) 不支持事件处理程序,因此我无法使用异步调用。无论如何,我的问题是,在发送事件之前,我想显示一条 请稍候消息,在收到响应后我想再次隐藏它。
function sendRequest() {
// make please wait visible
document.getElementById("pleasewait").style.display = "block";
console.log("pleasewait visible.");
var XHR = new XMLHttpRequest();
// synch call
XHR.send(sendData);
// suppose it takes 20-30 seconds
console.log("response received :" + XHR.responseText);
XHR.open('POST', 'url', false);
// make please wait hidden
document.getElementById("pleasewait").style.display = "none";
}
但是,当我 运行 它时,pleasewait 元素在我们收到响应(不是在发送之前)时可见,并且即使该过程需要 20-30 秒也会立即再次隐藏。控制台消息以正确的顺序显示,但请稍候元素未正确更新。我尝试了一些 setTimeouts 但没有期望的结果。我无法添加一些 jsfiddle,因为很难在远程上实现 ajax 请求处理程序。
Browsers will freeze when doing synchronous ajax request hence the
synchronous
request prevents the display re-flow!
我建议的唯一解决方案是使用 setTimeout
,持续时间 0
!
function sendRequest() {
document.getElementById("pleasewait").style.display = "block";
setTimeout(function() {
var XHR = new XMLHttpRequest();
XHR.send(sendData);
console.log("response received :" + XHR.responseText);
XHR.open('POST', 'url', false);
document.getElementById("pleasewait").style.display = "none";
}, 0);
}
注: Here是一些相关资料!