![](/img/trans.png)
[英]how to prevent to send ajax request while another ajax request is processing?
[英]Does Ajax block the window while processing the request?
我正在發出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',false);
。
我認為您open
電話是錯誤的。 第三個參數(布爾值)指示請求是否異步。
在這里考慮完整的文檔: http : //www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
ref.open('POST','x.jsp',true);
應該解決你的問題。
問候
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.