1. 程式人生 > >JS高程3:Ajax與Comet-進度事件、跨源資源共享

JS高程3:Ajax與Comet-進度事件、跨源資源共享

訪問 document www. logs 計算 table 不能 發生 ble

有以下 6 個進度事件

? loadstart:在接收到響應數據的第一個字節時觸發。
? progress:在接收響應期間持續不斷地觸發。
? error:在請求發生錯誤時觸發。
? abort:在因為調用 abort()方法而終止連接時觸發。
? load:在接收到完整的響應數據時觸發。
? loadend:在通信完成或者觸發 error、 abort 或 load 事件後觸發。

每個請求都從觸發 loadstart 事件開始,接下來是一或多個 progress 事件,然後觸發 errorabort load 事件中的一個,最後以觸發 loadend 事件結束。

目前瀏覽器只支持前五個進度事件。

load事件

var xhr = createXHR();
xhr.onload = function(){
	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);

progress事件

這個事件會在瀏覽器接收新數據期間周期性地觸發。

onprogress 事件處理程序會接收到一個 event 對象,其 target 屬性是 XHR 對象,但包含著三個額外的屬性:

lengthComputableposition totalSize

其中, lengthComputable是一個表示進度信息是否可用的布爾值, 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");
	if (event.lengthComputable){
		divStatus.innerHTML = "Received " + event.position + " of " +
		event.totalSize +" bytes";
	}
};
xhr.open("get", "altevents.php", true);
xhr.send(null);

如果響應頭部中包含Content-Length 字段,那麽也可以利用此信息來計算從響應中已經接收到的數據的百分比。

跨源資源共享

CORSCross-Origin Resource Sharing,跨源資源共享)
定義了在必須訪問跨源資源時,瀏覽器與服務器應該如何溝通。
CORS 背後的基本思想,就是使用自定義的 HTTP 頭部讓瀏覽器與服務器進行溝通,從而決定請求或響應是應該成功,還是應該失敗。
IE對CORS的實現

微軟在 IE8 中引入了 XDRXDomainRequest)類型。

? cookie 不會隨請求發送,也不會隨響應返回。
? 只能設置請求頭部信息中的 Content-Type 字段。
? 不能訪問響應頭部信息。
? 只支持 GET 和 POST 請求。

發送請求報文

var xdr = new XDomainRequest();
xdr.onload = function(){
	alert(xdr.responseText);
};
xdr.open("get", "http://www.somewhere-else.com/page/");
xdr.send(null);

檢測錯誤

var xdr = new XDomainRequest();
xdr.onload = function(){
	alert(xdr.responseText);
};
xdr.onerror = function(){
	alert("An error occurred.");
};
xdr.open("get", "http://www.somewhere-else.com/page/");
xdr.send(null);

其他瀏覽器CORS的實現

var xhr = createXHR();
xhr.onreadystatechange = function(){
	if (xhr.readyState == 4){
		if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
			alert(xhr.responseText);
		} else {
			alert("Request was unsuccessful: " + xhr.status);
		}
	}
};
xhr.open("get", "http://www.somewhere-else.com/page/", true);
xhr.send(null);

IE 中的 XDR 對象不同,通過跨域 XHR 對象可以訪問 status statusText 屬性,而且還支
持同步請求。跨域 XHR 對象也有一些限制,但為了安全這些限制是必需的。以下就是這些限制

? 不能使用 setRequestHeader()設置自定義頭部。
? 不能發送和接收 cookie。
? 調用 getAllResponseHeaders()方法總會返回空字符串。

JS高程3:Ajax與Comet-進度事件、跨源資源共享