当前位置: 移动技术网 > IT编程>脚本编程>Ajax > AJAX请求类

AJAX请求类

2017年12月12日  | 移动技术网IT编程  | 我要评论
复制代码 代码如下:

// ajax类
function ajaxrequest() {
 var xmlobj = false;
 var cbfunc,objself;
 objself=this;
 try { xmlobj=new xmlhttprequest; }
 catch(e) {
  try { xmlobj=new activexobject("msxml2.xmlhttp"); }
  catch(e2) {
   try { xmlobj=new activexobject("microsoft.xmlhttp"); }
   catch(e3) { xmlobj=false; }
  }
 }
 if (!xmlobj) return false;
 this.method="post";
 this.url;
 this.async=true;
 this.content="";
 this.callback=function(cbobj) {return;}
 this.send=function() {
  if(!this.method||!this.url||!this.async) return false;
  xmlobj.open (this.method, this.url, this.async);
  if(this.method=="post") xmlobj.setrequestheader("content-type","application/x-www-form-urlencoded");
  xmlobj.onreadystatechange=function() {
   if(xmlobj.readystate==4) {
    if(xmlobj.status==200) {
     objself.callback(xmlobj);
    }
   }
  }
  if(this.method=="post") xmlobj.send(this.content);
  else xmlobj.send(null);
 }
}


ajax请求类
by hotheart(热血心肠)
site: http://www.xujiwei.cn/
blog: http://www.xujiwei.cn/blog/


类名:ajax

创建方法:var ajaxobj=new ajax;,如果创建失败则返回false

属性:method  -  请求方法,字符串,post或者get,默认为post
   url         -  请求url,字符串,默认为空
   async     -  是否异步,true为异步,false为同步,默认为true
   content -  请求的内容,如果请求方法为post需要设定此属性,默认为空
   callback  - 回调函数,即返回响应内容时调用的函数,默认为直接返回,回调函数有一个参数为xmlhttprequest对象,即定义回调函数时要这样:function mycallback(xmlobj)

方法:send()     -  发送请求,无参数


一个例子:
<script type="text/javascript" src="ajaxrequest.js"></script>
<script type="text/javascript">
var ajaxobj=new ajaxrequest;    // 创建ajax对象
ajaxobj.method="get";   // 设置请求方式为get
ajaxobj.url="default.asp"  // url为default.asp
// 设置回调函数,输出响应内容
ajaxobj.callback=function(xmlobj) {
     document.write(xmlobj.responsetext);
}
ajaxobj.send();    // 发送请求
</script>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网