var Ajax={};
Ajax._xmlHttp = new (window.ActiveXObject||window.XMLHttpRequest)("Microsoft.XMLHTTP");
Ajax._xmlHttp.onreadystatechange=function(){
if(this.readyState==4&&this.status==200)
Ajax._fun(this.responseText);
}
Ajax.get=function(_url,_fun,_bool){
this._fun=_fun || function(){};
this._xmlHttp.open("GET",_url,_bool||false);
this._xmlHttp.send(null);
}
Ajax.post=function(_url,_data,_fun,_bool){
var obj=this,xhp=obj._xmlHttp;
obj._fun=_fun || function(){};
xhp.open("POST",_url,_bool||false);
xhp._xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhp._xmlHttp.send(_data);
}
Ajax.get("ajax.html",function(v){
alert(v)
});
经过2次修改最终是这个样子
1 <html>
2 <head></head>
3 <body>
4 <script type="text/javascript">
5 var Ajax={};
6 Ajax._xmlHttp =function(){ returnnew (window.ActiveXObject||window.XMLHttpRequest)("Microsoft.XMLHTTP");}
7 Ajax._addEventToXhp =function(xhp,fun,isxml){
8 xhp.onreadystatechange=function(){
9 if(xhp.readyState==4&&xhp.status==200)
10 fun(isxml?xhp.responseXML:xhp.responseText);
11 }
12 }
13 Ajax.get=function(url,fun,isxml,bool){
14 var xhp =this._xmlHttp();
15 this._addEventToXhp(xhp, fun ||function(){} ,isxml);
16 xhp.open("GET",url,bool);
17 xhp.send(null);
18 }
19 Ajax.post=function(url,data,fun,isxml,bool){
20 var xhp =this._xmlHttp();
21 this._addEventToXhp(xhp, fun ||function(){},isxml);
22 xhp.open("POST",url,bool);
23 xhp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
24 xhp.send(data);
25 }
26
27
28
29 //demo get 操作
30 Ajax.get("ajax.html",function(v){
31 alert(v)
32 });
33
34 Ajax.get("robots.txt",function(v){
35 document.write(v)
36 });
37
38
39
40 </script>
41 </body>
42 </html>
编辑器加载中...
Ajax._xmlHttp.onreadystatechange=function(){
if(this.readyState==4&&this.status==200)
Ajax._fun(this.responseText);
}
这里面的 this 在ie 中 竟然不是 Ajax._xmlHttp 而是 windows
这个ie 真的很烦人
更改为 下面代码 解决问题了
Ajax._xmlHttp.onreadystatechange=function(){
var xhp = Ajax._xmlHttp;
if(xhp.readyState==4&&xhp.status==200)
Ajax._fun(xhp.responseText);
}
完整代码如下:
<html>
<head></head>
<body>
<script type="text/javascript">
var Ajax={};
Ajax._xmlHttp =new (window.ActiveXObject||window.XMLHttpRequest)("Microsoft.XMLHTTP");
Ajax._xmlHttp.onreadystatechange=function(){
var xhp = Ajax._xmlHttp;
if(xhp.readyState==4&&xhp.status==200)
Ajax._fun(xhp.responseText);
}
Ajax.get=function(url,fun,bool){
this._fun=fun ||function(){};
this._xmlHttp.open("GET",url,bool||false);
this._xmlHttp.send(null);
}
Ajax.post=function(url,data,fun,bool){
var obj=this,xhp=obj._xmlHttp;
obj._fun=fun ||function(){};
xhp.open("POST",url,bool||false);
xhp._xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhp._xmlHttp.send(data);
}
Ajax.get("ajax.html",function(v){
alert(v)
});
</script>
</body>
</html>
学习了