XMLHttpRequest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 封装xhr对象,兼容各个版本
function createXHR() {
// 判断游览器是否将XMLHttpRequest作为本地对象实现,针对IE7,Firefox。opera等
if (typeof XMLHttpRequest != "undefined") {
return new XMLHttpRequest();
} else if (typeof ActiveXObject != "undefined") {
// 将所有可能出现的ActiveXObject版本放在一个数组中
var xhrArr = ["Microsoft.XMLHTTP", "MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP.2.0"
];
var xhr=null;
// 遍历创建XMLHttpRequest对象
var len=xhrArr.length;
for(var i=0;i<len;i++) {
try{
xhr= new ActiveXObject(xhrArr[i]);
break;
}
catch(ex) {
throw("ActiveXObject版本不支持");
}
}
return xhr;
}else {
throw new Error("No XHR object availabel.")
}
}

var xhr=createXHR();
console.log(xhr);

简易版本

1
2
3
4
5
6
var xhr;
if(window.XMLHttpRequest) {
xhr=new XMLHttpRequest();
}else {
xhr=new ActiveXObject("Microsoft.XMLHTTP")
}