function createXHR(){
//檢測原生XHR對象是否存在,若是存在剛返回它的新實例;
//若是不存在,則檢測ActiveX對象;
//若是兩個都不存在,就拋出一個錯誤。
if(typeof XMLHttpRequest != "undefined"){
return new XMLHttpRequest();
}else if(typeof ActiveXObject != "undefined"){
//適合IE7以前的版本
if(typeof arguments.callee.activeXString != "string"){
var versions = ["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML.XMLHttp"];
for(var i=0,len=versions.length; i<len; i++){
try{
var xhr = new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
return xhr;
}catch (ex){
//跳過
}
}
}
return new ActiveXObject(arguments.callee.activeXString);
}else{
throw new Error("No XHR object available.");
};
}對象
//建立XHR對象
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);
}
}
} get//讀取example文本
xhr.open("get","example.txt",true);
xhr.send(null);string