FormData:
// 为序列化表单以及创建与表单格式相同的数据提供了便利
var data = new FromData();
data.append("name", "Nicholas");// 使用FormData标准化数据后,发送到服务器
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("post", "postexample.pht", ture);
var form = document.getIEmentById("user-info");
xhr.send(new FormData(form));
超时设定:
// 仅适用于IE8
var xhr = createXHR();
xhr.onreadystatechange = function() {if( xhr.readyState == 4) {try {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 = 1* 1000; // 超时设置为1秒
xhr.ontimeout = function () {alert("Request did not return in a second.");
};
xhr.send(null);
ouverrideMimeType方法:
// 用于重写XHR响应的MIME类型
var xhr = createXHR();
xhr.open("get", "text.php", true);
xhr.overriderMimeType("text/xml");
xhr.send(null);// 注:若服务器返回的MIME类型是text/plain,通过overrideMimeType重写为 text/xml 类型,便于处理
进度事件:
// loadstart: 在接收到相应数据的第一个字节时触发
// progress: 在接收响应期间持续不断地触发
// error: 在请求发生错误时触发
// abort:在因为调用abort()方法而终止连接时触发
// load: 在接收到完整的响应数据时触发
// loadend: 在通信完成或者触发error、abort或load事件后触发// load事件
var xhr = creatXHR();
xhr.onload = function() {if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {alert(xhr.responseText);} else {alert("Request was unsuccessful: " + xhr.stauts);}
};
xhr.open("get", "altevents.php", true);
xhr.send(null);// progress事件
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);// 注1:onprogress事件会在浏览器接收新数据期间周期性地触发,其事件处理程序会接收到一个event对象
// 注2:event对象有3个属性:
// lengthComputable:表示进度信息是否可用的布尔值
// postion:已经接收到的字节数
// totalSize:根据Content-Length响应头部确定的预期字节数
跨域资源共享: (Cross-Origin Resource Sharing,CORS)是W3C的一个工作草案,定义了在 必须访问跨域资源时,浏览器与服务器应该如何沟通.
// 首先要明确简单请求的概念,满足以下条件:
// (1)请求方法是HEAD、GET、POST之一
// (2)HTTP头部不超过以下几种字段:
// ·Accept:告诉服务器能够发送哪些媒体类型
// ·Accept-Language:告诉服务器能够发送哪些语言
// ·Content-Language:理解主体时最适宜使用的自然语言
// ·Last-Event-ID: ...未找到
// ·Content-Type:(只限于application/x-www-form-unlencoded、multipart/form-data、text/plain)// 对于简单请求,在头信息中,增加一个Origin字段
GET /cors HTTP/1.1
Origin: http://api.bob.com // 用于说明本次请求来自哪个源(协议 + 域名 + 端口)
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0 ...// 如果Origin指定的源,不在许可范围内,服务器会返回一个正常(注意是正常的)的HTTP.
// 当浏览器发现响应报文中没有Access-Control-Allow-Origin字段.就知道请求出错了,从而调用xhr.onerror事件处理函数
// 如果Origin指定的源的域名在许可范围内,服务器返回响应,响应首部多出几个字段如下:
Access-Control-Allow-Origin: http://api.bob.com // 表示接收该域源的请求
Access-Control-Allow-Credentials: true // 表示是否允许发送Cookie
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset = utf-8
IE对CORS的实现: 微软在IE8中引入了XDR类型,用于实现安全可靠建的跨域通信
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);// 注:通过xdr方法请求的数据,没有响应码,只有error事件.// xdr的contentType属性,用来表示发送数据的格式
var xdr = new XDomainRequest();
xdr.onload = function() {alert(xdr.responseText);
};
xdr.onerror = function () {alert("An error occurred.");
};
xdr.open("post", "http://www.somewhere-else.com/page/");
xdr.contentType = "applicatin/x-www.form-urlencoded";
xdr.send("name1=value1&name2=value2");
其他浏览器对CORS的实现:
// 使用原生的XHR对象,在传入url的时候,传入绝对URL即可.
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);
跨浏览器的CORS:
// 检测XHR是否支持CORS的最简单方式,就是检查是否存在withCredentials属性.再结合检测XDomainRequest对象是否存在,即可实现兼容.
function createCORSRequest (method, url) {var xhr = new XMLHttpRequest();if ("withCredentials" in xhr) {xhr.open(method, url, true);} else if ( typeof XDomainRequest != "undefined") {xhr = new XDomainRequest();xhr.open(method, url);} else {xhr = null;}return xhr;
}
var request = createCORSRequest("get", "http://www.somewhere-else.com/page/");
if(request) {request.onload = function () {// 对 request.responseText 进行处理};request.send();
}
参考《JavaScript高级程序设计》(第3版)P578~P586
参考 阮一峰-跨域资源CORS详解
参考 《HTTP权威指南》P73、 P76