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

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

一、超時設定 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); 二、加載事件 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屬性,才能肯定數據是否真的已經可用了。 三、進度事件 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);
相關文章
相關標籤/搜索