支持xhr瀏覽器:超時設定、加載事件、進度事件


各個瀏覽器雖然都支持xhr,但還是有些差異。 

1、超時設定 IE8為xhr對象添加了一個timeout屬性,表示請求在等待響應多少毫秒后就終止。再給timeout這只一個數值后,如果在規定的時間內瀏覽器還沒有接收到響應,那么就會觸發timeout事件,進而會調用ontimeout事件處理程序。 
var xhr = creatXHR(); xhr.onreadystatechange = function(event){ try { if(xhr.readyState ==4){ if((xhr.status >= 200 && xhr.status <300) || xhr.status == 304){ alert(xhr.responseText); } else { alert("Request was unsuccessful:" + xhr.status); } } } catch(ex){ // 假設ontimeout事件處理程序處理 } }; 
xhr.open("get" , "timeout.php" , true); xhr.timeout = 1000; xhr.ontimeout = function(){ alert("Request did not return in a second."); }; xhr.send(null); 
2、加載事件 
Firfox在實現XHR對象的某個版本是時,曾致力於簡化異步交互模型。於是引入load事件,用以代替readystatechange事件。響應接收完畢后將觸發load事件,因此也就沒有必要去檢查readystate屬性了。最終結果為: var xhr = creatXHR(); xhr.onload = function(event){ if((xhr.status >= 200 && xhr.status <300) || xhr.status == 304){ alert(xhr.responseText); } else { alert("Request was unsuccessful:" + xhr.status); } }; xhr.open("get","altevents.php",true); xhr.send(null); 
只要瀏覽器接收到服務器的響應,不管其狀態如何,都會觸發load事件。而這意味着你必須檢查status屬性,才能確定數據是否真的已經可用了。 
3、進度事件 
Mozilla對XHR的另一個革新是添加了progress事件,這個時間會在瀏覽器接受新數據期間周期性的觸發,而onprogress事件處理程序會接收到一個event對象,其target屬性是XHR對象,但包含着兩個額外的屬性:position和totalSize。其中position表示已經接受的字節數,totleSize表示根據Content-Length響應頭部確定的預期字節數。 var xhr = creatXHR(); xhr.onload = function(event){ if((xhr.status >= 200 && xhr.status <300) || xhr.status == 304){ alert(xhr.responseText); } else { alert("Request was unsuccessful:" + xhr.status); } }; xhr.onprogress = function(event){ var.divStatus = document.getElementById("status"); divStatus.innerHTML = "Received" + event.position + "of" + event.totalSize +"bytes"; }; 
xhr.open("get","altevents.php",true); xhr.send(null);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM