一个AJAX类代码
程序员文章站
2022-06-24 16:17:15
基本用法: 复制代码 代码如下: var ajax = new ajaxobj(url); ajax.addlistener(200, function(r){ alert...
基本用法:
var ajax = new ajaxobj(url);
ajax.addlistener(200, function(r){
alert(r);
});
ajax.send();
也可以连续调用:
var ajax = new ajaxobj(url).addlistener(200, function(r){
alert(r);
}).send();
另外还支持自定义的post或get方式请求,以及监视不同的http状态码,自己看代码琢磨吧 :)
完整代码:
ajaxobj = function(url, method, content){
this.r = null;
this.url = url;
this.method = method;
this.content = content;
this.header = {};
this.header["connection"] = "close";
this.header["content-type"] = "application/x-www-form-urlencoded";
var self = this;
if(window.xmlhttprequest){
this.r = new xmlhttprequest();
}else if(window.activexobject){
try {
this.r = new activexobject("msxml2.xmlhttp");
} catch(e) {
try{
this.r = new activexobject("microsoft.xmlhttp");
} catch(e) {
}
}
}
this.addlistener = function(http_status, func){
if(!this.l)
this.l=[];
this.l[http_status] = func;
return this;
};
this.setheader = function(name, value){
this.header[name] = value;
this.r.setrequestheader(name, value);
return this;
};
this.send = function(){
if(this.method != "post" && this.method != "get")
this.method = "get";
this.r.open(this.method, this.url, true);
for(var h in this.header) {
this.r.setrequestheader(h, this.header[h]);
}
this.r.send(this.content);
};
if(this.r) this.r.onreadystatechange = function(){
if(self.r.readystate == 4 && self.l[self.r.status] != null)
self.l[self.r.status](self.r.responsetext);
};
};
复制代码 代码如下:
var ajax = new ajaxobj(url);
ajax.addlistener(200, function(r){
alert(r);
});
ajax.send();
也可以连续调用:
复制代码 代码如下:
var ajax = new ajaxobj(url).addlistener(200, function(r){
alert(r);
}).send();
另外还支持自定义的post或get方式请求,以及监视不同的http状态码,自己看代码琢磨吧 :)
完整代码:
复制代码 代码如下:
ajaxobj = function(url, method, content){
this.r = null;
this.url = url;
this.method = method;
this.content = content;
this.header = {};
this.header["connection"] = "close";
this.header["content-type"] = "application/x-www-form-urlencoded";
var self = this;
if(window.xmlhttprequest){
this.r = new xmlhttprequest();
}else if(window.activexobject){
try {
this.r = new activexobject("msxml2.xmlhttp");
} catch(e) {
try{
this.r = new activexobject("microsoft.xmlhttp");
} catch(e) {
}
}
}
this.addlistener = function(http_status, func){
if(!this.l)
this.l=[];
this.l[http_status] = func;
return this;
};
this.setheader = function(name, value){
this.header[name] = value;
this.r.setrequestheader(name, value);
return this;
};
this.send = function(){
if(this.method != "post" && this.method != "get")
this.method = "get";
this.r.open(this.method, this.url, true);
for(var h in this.header) {
this.r.setrequestheader(h, this.header[h]);
}
this.r.send(this.content);
};
if(this.r) this.r.onreadystatechange = function(){
if(self.r.readystate == 4 && self.l[self.r.status] != null)
self.l[self.r.status](self.r.responsetext);
};
};
下一篇: Vue组件创建和传值的方法