复制代码 代码如下:
<script type="text/javascript">
function Ajax(){
var xhr;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
try{xhr=new ActiveXObject("MSXML2.XMLHTTP.6.0");}catch(e){}
try{xhr=new ActiveXObject("MSXML2.XMLHTTP");}catch(e){}
}
if(!xhr) return;
this.Xhr=xhr; //用属性存储XMLHttpRequest对象的实例
}
Ajax.prototype.send=function(url,options){
if(!this.Xhr) return;
var xhr=this.Xhr;
var aborted=false;
var _options={ //提供默认值
method:"GET",
timeout:5000,
onerror:function(){},
onsuccess:function(){}
};
for(var o in options){ //覆盖掉原来的默认值
_options[o]=options[o];
}
function checkForTimeout(){ //检查是否超时的情况
if(xhr.readyState!=4){
aborted=true;
xhr.abort(); //取消本次传输
}
}
//在规定的时间内检查readyState属性的值
setTimeout(checkForTimeout,_options.timeout);
function onreadystateCallback(){
if(xhr.readyState==4){
/*
* 注释:状态码在200内表示成功,300内表示重定向,400内是客户端错误,500是服务器端错误
*/
if(!aborted && xhr.status>=200 && xhr.status<300){ //检查aborted属性是否超时
_options.onsuccess(xhr);
}else{
_options.onerror(xhr);
}
}
}
xhr.open(_options.method,url,true);
xhr.onreadystatechange=onreadystateCallback;
xhr.send(null);
}
var ajax=new Ajax();
ajax.send("test.php",{method: GET ,timeout:100,onerror:onerror,onsuccess:onsuccess});
function onerror(xhr){
alert("Timeout");
}
function onsuccess(xhr){
alert(xhr.responseText);
}
</script>