XMLHttpRequest 1级只是把已有的XHR对象的实现细节描述出来,而XMLHttpRequest 2级则进一步发展了XHR;并非所有浏览器都完整实现了XMLHttpRequest2级规范,但是所有浏览器都实现了他规定的部分内容;
1:FormData
FormData类型为序列化表单提供了遍历;下面的代码创建了一个FormData对象,并想其中添加了一些数据
这个append方法接受2个参数:键跟值,分别对应表单字段的名字跟表单字段中包含的值;可以添加任意多个简直对儿;
var data=new FormData();
data.append('name','Nicholas')
也可以通过向FormData构造函数中传入表单元素;
var xhr=new XMLHttpRequest()();
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','example.php',true);
var form=document.getElementById('user-info')
xhr.send(new FormData(form));
使用FormData的方便之处体现在不必明确的在XHR对象上设置请求头部;XHR对象能够识别传入的数据类型是FormData的实例,并且配置适当的头部信息;支持FormData的浏览器有firefox4+,Safari5+,Andriid3+,webkit
2:超时设定
IE8为XHR对象添加了一个timeout属性,表示请求在等待响应多少毫秒之后就终止;在给timeout设置一个数值后,如果在规定时间内浏览器还没有接收到响应,那么就会触发timeout事件,调用ontimeout处理程序;XMLHttpRequest2级规范也收入进来了;
forefox,google都实现了。IE8+
var xhr=new XMLHttpRequest()();
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('post','example.php',true);
xhr.timeout=1000; //将超时事件设置为1S
xhr.ontimeout=function(){ //请求终止时,会执行ontimeout事件处理程序
alert('request did not return in a second!')
}
xhr.send();
超时以后在访问status属性就会导致错误;
3:overrideMimeType
比如服务器返回的MIME类型是text/plain,但是数据中实际包含的是XML。根据MIME类型,即使数据是XML,responseXML属性中任然是null;通过调用overrideMimeType()方法,可以保证吧响应当做XML,而非纯文本来处理;该方法必须卸载send方法之前调用
var xhr=new XMLHtttpRuquest();
xhr.open('get','text.php',true)
xhr.overrideMimeType('text/xml')
xhr.send(null)