XMLHttpRequest2 异步 ajax

XMLHttpRequest1只是对已经存在的xhr对象细节进行规范定义, XMLHttpRequest2升级了该对象。

 

FormData 类型
可以用在xhr传输的时候,把表单序列化或者将数据以表单格式传输
Var data = new FormData()
data. append("name","xiangwei")

 

直接把表单传进入进行序列化:
var data = new FormData(document. forms[0]);
当你建立好一个 FormData实例以后,就可以把它放到send方法里发送给服务器了:
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.php”, true);
var form = document.getElementById(“user-info”);
xhr.send(new FormData(form))

 

还有一个好处是formdata类型不需要手动设置内容类型,xhr会自动识别并且添加header。

 

Timeouts 超时
这个属性用来设置等待相应的时间,超过了还没有接收到服务器响应的话,就会触发timeout事件,该请求也会中断。但是readystate还是会改为4,不过在过时以后接入state属性会产生错误,需要捕获,目前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){
//assume handled by ontimeout
}
}
};
xhr.open(“get”, “timeout.php”, true);
xhr.timeout = 1000; //set timeout for 1 second (IE 8+ only)
xhr.ontimeout = function(){
alert(“Request did not return in a second.”);
};
xhr.send(null);

 

overrideMimeType()方法
因为服务器返回的响应MIME类型决定了xhr对象如何处理数据,该方法可以覆盖掉服务器返回的类型,用自己定义的类型来处理。

 

例如返回的数据为xml但是服务器给的MIME类型为text/plain,那么responseXML属性就是null:
var xhr = createXHR();
xhr.open(“get”, “text.php”, true);
xhr.overrideMimeType(“text/xml”);
xhr.send(null);
注意的是,要在send之前调用。

posted on 2016-01-28 15:08  迷茫小飞侠  阅读(266)  评论(0编辑  收藏  举报

导航