zl程序教程

您现在的位置是:首页 >  前端

当前栏目

给初学ajax的人ajax函数代码

AJAX代码 函数 初学
2023-06-13 09:14:19 时间
复制代码代码如下:

/*
调用方式:
1.POST方式
vartxt=escape(sender.value);//document.getElementById("<%=txtName.ClientID%>").value);
vardata="name="+txt+"&pwd="+txt;
varoption={"url":"handler/Handler.ashx"
,"action":"POST"
,"callback":function(){
if(xmlHttp.readyState==4){//服务器给了回应
if(xmlHttp.status==200){//服务正确响应
alert(xmlHttp.responseText);
}
xmlHttp=null;//回收资源
}
   }
,"data":data
};
ajax(option);
2.GET方式
vartxt=escape(sender.value);//document.getElementById("<%=txtName.ClientID%>").value);
varoption={"url":"handler/Handler.ashx&name="+txt+"&pwd="+txt
,"action":"POST"
,"callback":function(){
if(xmlHttp.readyState==4){//服务器给了回应
if(xmlHttp.status==200){//服务正确响应
alert(xmlHttp.responseText);
}
xmlHttp=null;//回收资源
}
   }
};
ajax(option);
*/
functionajax(option){
createXMlHttpRequest();//创建xmlHttpRequest对象
if(option!=null&&option!=undefined){
if(option.url==null&&option.url==undefined){
xmlHttp=null;
alert("缺少必要参数option.url");
return;
}
if(option.action==null&&option.action==undefined){
xmlHttp=null;
alert("缺少必要参数option.action");
return;
}
xmlHttp.open(option.action,option.url,true);
if(option.contentType!=null&&option.contentType!=undefined){
xmlHttp.setRequestHeader("Content-Type",option.contentType);
}else{
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
if(option.callback!=null&&option.callback!=undefined){
xmlHttp.onreadystatechange=option.callback;
}
if(option.action.toUpperCase()=="POST"){
xmlHttp.send(option.data);
}else{
xmlHttp.send(null);
}
}
}
varxmlHttp;//调用完成后最好回收下xmlHttp=null;
/*获取元素*/
functiong(arg){
vart=document.getElementById(arg);
if(null!=t&&t!=undefined){
returnt;
}
t=document.getElementsByName(arg);
if(null!=t&&t!=undefined){
returnt;
}
t=document.getElementsByTagName(arg);
if(null!=t&&t!=undefined){
returnt;
}
}
/*创建ajax请求对象*/
functioncreateXMlHttpRequest(){
try{//Firefox,Chrome,Surfri,Opera+8
xmlHttp=newXMLHttpRequest();
}
catch(ie){
try{//IE6+
xmlHttp=newActiveXObject("Msxml2.XMLHTTP");
}catch(ie){
xmlHttp=newActiveXObject("Microsoft.XMLHTTP");
}
}
returnxmlHttp;
}