你的位置: Kiyo'Space首页 JavaScript/Jscript 阅读文章 欢迎留下您的足迹

ajax 工具类

[ JavaScript/Jscript ] 分享
以下是引用片段:

function Ajax(method,url,param,ft,fun)
{
 this.xhr=this.getxhr();
 this.docType=ft;
 switch(method.toLowerCase())
 {
  case "post":this.post(url,param);break;
  case "get":this.get(url,param);break;
 }
 this._readystate=null;
 this.fun=fun;
 
}

Ajax.prototype.getxhr=function()
{
 var ms=['Microsoft.XMLHttp','MSXML.XMLHttp','MSXML2.XMLHttp','MSXML3.XMLHttp'];
    if(window.ActiveXObject)
    { 
  try{
            for(var i=0;i<ms.length;i++)
         {
            return new ActiveXObject(ms[i]);
         }
     }
  catch(e){}
 }
 else if(window.XMLHttpRequest)
 {
  var req=new XMLHttpRequest();
  
  if(req.overrideMimeType)
  {
   req.overrideMimeType("text/xml");
  }
  
 }
 return req;
}

Ajax.prototype.post=function(url,param)
{
 var rc=Math.round(Math.random()*999);
 if(url.indexOf("?")>=0)
 {
  url+="&arnd="+rc;
 }
 else
 {
  url+="?arnd="+rc;
 }
 this.xhr.open("post",url,true);
 var obj=this;
 this.xhr.onreadystatechange=function(){obj.call_(obj)}
 this.xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
 this.xhr.send(param);
}

Ajax.prototype.get=function(url,param)
{
 var rc=Math.round((Math.random()*999));
 if(url.indexOf("?")>=0)
 {
  url+="&"+param+"&arnd="+rc;
 }
 else
 {
  url+="?"+param+"&arnd="+rc;
 }
 this.xhr.open("get",url,true);
 var obj=this;
 this.xhr.onreadystatechange=function(){obj.call_(obj)}
 this.xhr.send();
}

Ajax.prototype.call_=function(req)
{
 if(req.xhr.readystate==4)
 {
  if(req.xhr.status==200)
  {
   if(req.docType.toLowerCase()=="xml")
   {
    eval(req.fun+"(req.xhr.responseText)");
   }
   else
   {
    eval(req.fun+"(req.xhr.responseText)");
   }
  }
 }
}

 

From:http://blog.csdn.net/hanpoyangtitan/archive/2007/06/18/1656711.aspx

没有评论

  • (Required)
  • (Required, will not be published)