要使用xhr对象,需要编写一个函数。
方法一:优点简洁,在大部分ie版本上都能运行,但是没有版本检测,不知道低版本的情况还行不行。
var http_request;
function creatxhr(){
if(window.activexobject){
http_request=new activexobject("microsoft.xmlhttp");
}else{
http_request=new xmlhttprequest();
}
}
方法二来自书《javascript高级程序设计(第3版)》
首先检测原生xhr对象是否存在,如果存在就返回它的新实例。如果不存在就检测activex对象。如果两种都不存在,就抛出错误。
关注if (typeof arguments.callee.activexstring != "string")这一句,如果有以前缓存的activexstring对象,下一次就不会执行if里面的东西。通过数组和for循环创建,很清晰,很严谨。
function createxhr() {
if (typeof xmlhttprequest != "undefined") {
return new xmlhttprequest(); //ie7+和其他浏览器支持的
} else if (typeof activexobject != "undefined") { //ie7-支持的
**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 (e) { //跳过
}
}
} return new activexobject(arguments.callee.activexstring); //返回activexobject对象
} else { //全部不支持,抛出错误
throw new error("no xhr object available!");
}
} var xhr = createxhr();
方法三网上看见的方法,考虑惰性函数的优点,一次检测之后重写构造方法。
在方法二的基础上加入惰性函数,构成方法三。
**惰性载入表示函数执行的分支只会在函数第一次掉用的时候执行,在第一次调用过程中,该函数会被覆盖为另一个按照合适方式执行的函数,这样任何对原函数的调用就不用再经过执行的分支了。**
哇!觉得惰性函数是真的好玩!
function createxhr() {
if (typeof xmlhttprequest != "undefined") { //在第一次执行的时候重写createxhr函数
createxhr = function() {
return new xmlhttprequest();
};
} else if (typeof activexobject != "undefined") {
createxhr = function() {
if (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 {
createxhr = function() {
throw new error("no xhr object available.");
};
}
return createxhr();
}
var xhr = createxhr();
以上就是有关xmlhttprequest对象的详细内容。