一个封装的AJAX类

不知道你是否跟中国E盟技术频道的小编一样,給自己定个小目标,在年前写个一个封装的AJAX类,AJAX已然成为了前端开发最重要的“工具”之一,快跟随中国E盟小编一起往下了解吧。

用法:
newAjax().Request(url,cmd,async,method,postString,title)
参数:
url:请求页面URL(必填)
cmd:返回值处理函数(必填)
async:是否异步,(ture|false),默认true
method:请求方式,(post|get),默认get
postString:请求方式为post时,请求内容
title:请求内容标题

复制代码 代码如下:

//Ajax封装2007-3-13
functioncreateXMLHttpRequest(){
try{
if(window.XMLHTTPRequest){
returnnewXMLHttpRequest();
}
elseif(window.ActiveXObject){
returnnewActiveXObject("Microsoft.XMLHTTP");
}
}
catch(e){alert("XMLHttpRequest对象无法创建!请检查IE安全设置!");}
}
functionmessageDiv(t)
{
varv=document.createElement("
");
v.innerHTML=""+
""+
"style=\"padding:2px;border-top:1pxsolid#e1e1e1;border-left:1pxsolid#e1e1e1;border-bottom:1pxsolid#818181;border-right:1pxsolid#a1a1a1\">style=\"font-size:12px;background-color:#eeeeff;color:#227933;height:20px\">
"+
""+t+",连接未初始化...id=span1>>";
varl=document.getElementsByName("message").length;
v.style.cssText="position:absolute;bottom:"+(l*24)+"px;left:0px;display:none";
document.body.appendChild(v);
this.clear=function(){
document.body.removeChild(v);
varmsg=document.getElementsByName("message");
for(vari=0;imsg[i].parentNode.style.cssText="position:absolute;bottom:"+(i*24)+"px;left:0px";
}
}
this.showmsg=function(s){
v.style.display="";
v.all.Span1.innerHTML=s;
}
}
functionAjax(){
varx=newcreateXMLHttpRequest();
this.Request=function(url,cmd,async,method,postString,title){
if(method!="post")method="post";elsemethod="get";
if(async!=true)async=true;elseasync=false;
if(typeof(postString)!="string")postString="";
if(typeof(title)!="string")title="正在获取数据";elsetitle="正在获取"+title;
varmsgbox=newmessageDiv(title);
x.onreadystatechange=function()
{
if(async)switch(x.readystate){
case1:
msgbox.showmsg("正在初始化连接...");
return;
case2:
msgbox.showmsg("正在发送数据...");
return;
case3:
msgbox.showmsg("正在接收数据...");
return;
case4:
msgbox.showmsg("数据接收完成...");
if(x.status==200){
cmd(x.responseText);
msgbox.clear();
}
else{
msgbox.showmsg("请求失败,"+x.statustext+"("+x.status+")");
setTimeout(msgbox.clear,3000);
}
return;
}
}
x.open(method,url,async);
if(method=="post"){msgbox.showmsg("正在接收数据...");x.send(postString);}elsex.send();
if(!async){
msgbox.showmsg("数据接收完成...");
cmd(x.responseText);
msgbox.clear();
}
}
}
;i++){>
style=\"width:300px;\"id=message>

中国E盟技术小编已经成功完成了年前定下的目标,写下这篇一个封装的AJAX类,你也要努力了喔,更多关于AJAX的内容,可以多多关注下中国E盟技术频道,我们会不断的更新。