今天JS练手的时候,想封装一个发送AJAX请求的对象,当然,是想要兼容全浏览器的。代码如下: 
复制代码 代码如下:
 
var Ajax = { 
xhr: null, 
callback: null, 
XMLHttp: function() { 
var xmlhttp; 
//标准浏览器 
if(window.XMLHttpRequest) { 
try { 
xmlhttp = new XMLHttpRequest(); 
} 
catch(e) { 
alert('Unknown Ajax Error'); 
//console.log('Unknown Ajax Error'); 
} 
} 
//IE浏览器 
else { 
if(window.ActiveXObject) { 
try { 
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); 
} 
catch(e) { 
try { 
xmlhttp = new ActiveXObject('MSXML2.XMLHTTP'); 
} 
catch(e) { 
alert('Unknown Ajax Error'); 
//console.log('Unknown Ajax Error'); 
} 
} 
} 
} 
return xmlhttp; 
}, 
connect: function(paramsObj) { 
var PO = paramsObj; 
//判断传参合法性 
if(!(PO instanceof Object)) { 
alert('Ajax params illegal'); 
//console.log('Ajax params illegal'); 
return false; 
} 
else if(!(PO.url&&PO.method&&PO.callback)) { 
return false; 
} 
//初始化内部参数 
this.xhr = this.XMLHttp(); 
this.callback = PO.callback; 
//遍历params对象并生成url参数 
var requestParams = ''; 
if(PO.params) { 
for(key in Po.params) { 
requestParams += '&' + key + '=' + params[key]; 
} 
requestParams = requestParams.substr(1); 
} 
//发起Ajax请求 
try { 
var xhr = this.xhr; 
xhr.onreadystatechange = this.response; 
//POST请求处理 
if(PO.method.toLowerCase()=='post') { 
xhr.open('POST',PO.url,true); 
xhr.send(requestParams); 
} 
//GET请求处理 
else if(PO.method.toLowerCase()=='get') { 
xhr.open('GET',PO.url+'?'+requestParams,true); 
xhr.send(null); 
} 
} 
catch(e) { 
this.callback(null,-1); 
} 
}, 
response: function() { 
// 此段代码在全浏览器下测试通过 
// if(Ajax.xhr.readyState==4) { 
// if(Ajax.xhr.status=='200') { 
// Ajax.callback(Ajax.xhr.responseText); 
// } 
// else { 
// Ajax.callback(null,Ajax.xhr.status); 
// } 
// } 
// 
// 下面的代码在IE下失效(无报错,请求有相应,却没有返回结果),其它浏览器无此问题 
if(this.readyState==4) { 
if(this.status=='200') { 
Ajax.callback(this.responseText); 
} 
else { 
Ajax.callback(null,this.status); 
} 
} 
} 
}; 
//Ajax实例 
Ajax.connect({ 
url: 'test.html', 
method: 'GET', 
callback: function(data,err) { 
if(data!=null) { 
alert(data); 
// console.log(data); 
} 
else { 
alert(err); 
// console.log(err); 
} 
} 
}); 
新闻热点
疑难解答
图片精选