现在的位置: 首页 > 综合 > 正文

ajax 工具 类

2013年08月04日 ⁄ 综合 ⁄ 共 1531字 ⁄ 字号 评论关闭

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)");
   }
  }
 }
}

抱歉!评论已关闭.