Ajax comet XMLHttpRequest 异步

function createXHR() {

if (typeof XMLHttpRequest != “undefi ned”){
     return new XMLHttpRequest();
} else if (typeof ActiveXObject != “undefined”){                                                                                        ie6及以下只能使用activeX 对象,没有XMLHttpRequest
if (typeof arguments.callee.activeXString != “string”){
var versions = [“MSXML2.XMLHttp.6.0”, “MSXML2.XMLHttp.3.0”, “MSXML2.XMLHttp”], i, len;
 
for (i=0,len=versions.length; i < len; i++){
try {
new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
break;
} catch (ex){
                             //有错误就跳过
}
}    
}
     return new ActiveXObject(arguments.callee.activeXString);
} else {
     throw new Error(“No XHR object available.”);
}

}
var xhr = createXHR();
xhr.open(“get”, “example.php”, false);                                 这里的URL是相对于调用该代码的页面地址,调用open方法并没有发送请求,只是准备好一个要发送的请求
xhr.send(null);                                      该方法必须接受一个参数,作为发送给服务器的请求数据,如果没有数据需要发送给服务器,那么填null,不填有些浏览器会报错

 

当接收到服务器的响应之后,该XHR对象的属性就会带着数据回来啦,相关属性有:
responseText  — 返回的text就是响应的主体内容了
responseXML  —  如果响应有内容类型 “text/xml”or “application/xml”,则包含一个带有响应数据的XML Dom文档 
status   —   相应的HTTP状态
statusText  — HTTP状态的描述

 

判断响应状态,通常20几代表成功了部分数据已经返回,另外304表示那个资源没有被修改过,直接从浏览器缓存拿过来就可以
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {   
    alert(xhr.responseText);
} else {
    alert(“Request was unsuccessful: “ + xhr.status);
}
(浏览器兼容问题:Several browsers incorrectly report a 204 status code. ActiveX versions of XHR in Internet Explorer set statusto 1223 when a 204 is retrieved, and native XHR objects in Internet Explorer normalize 204 to 200. Opera reports a statusof 0 when a 204 is retrieved.)

 

当异步发送的时候,xhr对象有一个readystate可以指示出目前处于(请求/响应)循环的那个阶段
0  ---   请求未初始化
1  ---   服务器连接已建立
2  ---  请求已接收
3  ---  请求处理中
4  ---  请求已完成,且响应已就绪

 

当状态从一个进入另一个的时候,都会触发readystatechange事件,因此可以在此添加事件来检查:
var xhr = createXHR();
xhr.onreadystatechange = function() {                                                 //这个事件不会有event 对象,使用this因为scope作用域问题可能导致函数运行失败或者报错

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”, “example.txt”, true);
xhr.send(null);

 

在收到响应之前可以调用abort()来终止异步请求:
xhr.abort();
调用这个方法xhr对象就停止触发事件,阻止接入xhr上任何和响应数据相关的属性

 

HTTP  Headers
每一个请求和响应都伴随着一系列的header信息,xhr对象有一系列操作的方法

 

xhr请求发送的时候默认会带有的header(因浏览器而异,以下的是大部分浏览器都会发送的):
Accept  —  这个浏览器能够处理的内容类型
Accept-Charset  — 当前浏览器可以显示的字符集
Accept-Encoding  — The compression encodings handled by the browser.
Accept-Language  — 浏览器当前语言环境(中英文之类的)
Connection  — 当前浏览器和服务器之间的连接类型
Cookie  — Any cookies set on the page.
Host  — The domain of the page making the request.
Referer  — The URI of the page making the request. Note that this header is spelled incorrectly in the HTTP specification and so must be spelled incorrectly for compatibility purposes. (The correct spelling of this word is “referrer”.)
User-Agent  — The browser’s user-agent string

 

使用setRequestHeader()添加额外的header,注意使用的时候要在open之后,send之前:
...
xhr.open(“get”, “example.php”, true);
xhr.setRequestHeader(“MyHeader”, “MyValue”);
xhr.send(null);
...
不建议使用默认的header名字来发送信息(如:不要啊 xhr.setRequestHeader(“Accept”, “MyValue”);)  而且有些浏览器不允许覆盖

 

从xhr获取服务器响应的header信息:
var myHeader = xhr.getResponseHeader(“MyHeader”);
var allHeaders xhr.getAllResponseHeaders();

 

GET 请求(通常用来请求数据):
所有的键值对的名称和值都要先encodeURIComponent()编码,然后使用等号连接 ,下面这个函数就是添加参数到URL:
function addURLParam(url, name, value) {

url += (url.indexOf(“?”) == -1 ? “?” : “&”);
url += encodeURIComponent(name) + “=” + encodeURIComponent(value);
return url;

}

 

POST 请求(通常用来发送需要被存储的数据)
post请求的主体可以容纳大量数据,任何格式,通常发起的post请求不会被服务器当做表格提交来处理,直接读取未经处理的数据,但是可以模拟:
function submitData(){

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);
xhr.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);         //模拟表单提交时的内容类型
var form = document.getElementById(“user-info”);
xhr.send(serialize(form));

}
post请求开销会更多,发送同样的数据get比post快将近两倍

原文地址:https://www.cnblogs.com/chuangweili/p/5166322.html