JS高程3:Ajax与Comet-进度事件、跨源资源共享

有以下 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()方法总会返回空字符串。
原文地址:https://www.cnblogs.com/leomei91/p/7575345.html