先看調用方式:
複製代碼 代碼如下:
ajax.request("ajax.html",{v:Math.random(),num:1},function(data){
//do something
},'get');
方式好像jquery哦。。。還是覺得這樣調用方便些。。。
複製代碼 代碼如下:
var ajax = {
//Xmlhttprequest類
Xmlhttprequest :function() {
this.xhr =false;
},
//外部調用介面
request : function(url,data,callback,type) {
//每次都建立一個Xmlhttprequest的對象,使ajax調用互不影響
var xhr = new this.Xmlhttprequest();
xhr.request(url,data,callback,type);
}
}
//將{num:1,t:'a'}這種json資料格式轉為num=1&t=a這種字串形式
var json2str = function(data){
var _data = [];
for(var name in data) {
_data.push(name+"="+data[name]);
}
return _data.join('&');
}
//擴充Xmlhttprequest類的方法
ajax.Xmlhttprequest.prototype = {
//建立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){};
}
}
},
//回呼函數
fnCallback : function(callback){
if(this.xhr.readyState === 4 && this.xhr.status === 200) {
callback?callback(this.xhr.responseText):void(0);
}
},
//ajax請求
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);
}
}
這個類,肯定有不足的了,歡迎拍磚吧!每個人都有自己的習慣用法,最重要是適合用就行了!