Let’s look at the calling method first:
ajax.request( "ajax.html",{v:Math.random(),num:1},function(data){
//do something
},'get');
The method is like jquery. . . I still find it more convenient to call it this way. . .
var ajax = {
//Xmlhttprequest class
Xmlhttprequest :function() {
this.xhr =false;
},
//External call interface
request : function(url,data,callback,type) {
/ /Create an Xmlhttprequest object each time so that ajax calls do not affect each other
var xhr = new this.Xmlhttprequest();
xhr.request(url,data,callback,type);
}
}
//Convert the json data format {num:1,t:'a'} to the string format num=1&t=a
var json2str = function(data){
var _data = [];
for(var name in data) {
_data.push(name "=" data[name]);
}
return _data.join( '&');
}
//Methods to extend the Xmlhttprequest class
ajax. >if(window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else {
var a = ["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP. 5.0","Msxml2.XMLHTTP.4.0","Msxml2.XMLHTTP.3.0"];
for (var i=0,l=a.length;itry{
return new ActiveXObject(a[i]);
}catch(e){};
}
}
},
//Callback function
fnCallback: function(callback ){
if(this.xhr.readyState === 4 && this.xhr.status === 200) {
callback?callback(this.xhr.responseText):void(0);
}
},
//ajax request
request: function(url, data, callback, type){
var that = this;
var ispost = type ==='post'?true:false;
ispost?url:url = '?' json2str(data);
this.xhr = this.createXmlHttpRequest();
this.xhr.open(type,url,true);
ispost?this.xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"):'';
this.xhr.onreadystatechange = function(){that.fnCallback(callback);};
this.xhr.send(ispost?json2str(data):null);
}
}
There must be some shortcomings in this category, please feel free to give it a try! Everyone has their own customary usage, the most important thing is to use it appropriately!