我正在发出一个ajax请求,可能需要很长时间来处理服务器端。所以我想在请求处理时显示加载图像。但是在ajax请求时没有显示加载图像。
var ref = createAjaxRequest();//Ajax req is created here...
if(ref){
showLoadingImg();
ref.open('POST','x.jsp',false);
ref.onreadystatechange = eventStateChange;
ref.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ref.setRequestHeader("Connection", "keep-alive");
ref.send();
}
else{ alert("Your browser does not support this feature");
}
function eventStateChange(){
if(ref.readyState==4 ){
//processing response here......
hideLoadingImg();
}
}
function showLoadingImg();{
/* <div id="ajaxLoading">(with background image is in page)
It is displayed properly when I set display:inline
manually through developer tools of a browser.</div>
*/
document.getElementById('ajaxLoading').style.display='inline';
}
function hideLoadingImg();{
document.getElementById('ajaxLoading').style.display='none';
}
有什么问题吗?
我尝试调试并发现:
虽然
showLoadingImg()
是在open()
方法之前调用的,但是加载图像只有在ref.readyState==2之后才会显示在浏览器上
.但不幸的是,
readyState==2
和readyState==4
之间的时间间隔非常小,加载图像立即隐藏。
因此用户看不到加载图像...
所以,我怀疑的是,ajax 不会运行脚本,除非它进入 readyState==2
。
最佳答案
如果您将 async
设置为 false
,
XMLHttpRequest 会阻塞,就像您对此处的第三个参数所做的那样:ref.open('POST','x.jsp' ,假);
。
关于javascript - Ajax 在处理请求时是否会阻塞窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19184357/