First look at the calling mode:
Copy Code code as follows:
Ajax.request ("ajax.html", {v:math.random (), num:1},function (data) {
Do something
}, ' get ');
Way like jquery oh ... Still think this kind of call convenient ...
Copy Code code as follows:
var ajax = {
XMLHttpRequest class
Xmlhttprequest:function () {
THIS.XHR =false;
},
External calling interface
Request:function (Url,data,callback,type) {
Each time a XMLHttpRequest object is created so that the AJAX call does not affect
var xhr = new this. XMLHttpRequest ();
Xhr.request (Url,data,callback,type);
}
}
convert {num:1,t: ' A '} This JSON data format to num=1&t=a this string form
var json2str = function (data) {
var _data = [];
for (var name in data) {
_data.push (name+ "=" +data[name]);
}
Return _data.join (' & ');
}
Ways to extend the XMLHttpRequest class
Ajax. Xmlhttprequest.prototype = {
Create XMLHttpRequest
Createxmlhttprequest:function () {
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;i<l;i++) {
try{
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);
}
}
This class, there must be insufficient, welcome to the Brick Bar! Everyone has their own habits, the most important is the right to use it!