各瀏覽器雖然都支援 XHR(XMLHttpRequest),但在細節上仍存在差異。本文聚焦三個實用特性:超時控制、load 加載事件,以及 progress 進度事件。
IE8 為 XHR 對象新增了 timeout 屬性,用於指定請求等待響應多少毫秒後即中止。設定 timeout 後,若在規定時間內仍未收到響應,瀏覽器便會觸發 timeout 事件,進而呼叫 ontimeout 處理程序。
var xhr = createXHR();
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);
Firefox 在實現 XHR 的某個版本時,曾致力於簡化異步交互模型,於是引入 load 事件來取代 readystatechange。響應接收完畢後即觸發 load 事件,也就無需再反覆檢查 readyState 了。
var xhr = createXHR();
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(依 Content-Length 響應頭推算的預期字節數)。
var xhr = createXHR();
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);
藉由 progress 事件,我們得以實時呈現下載進度,大幅提升使用者對長耗時請求的等待體驗。