先看调用方式:
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;itry{
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);
}
}
这个类,肯定有不足的了,欢迎拍砖吧!每个人都有自己的习惯用法,最重要是适合用就行了!