今天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);
}
}
});
新聞熱點
疑難解答
圖片精選