您现在的位置: 万盛学电脑网 >> 程序编程 >> 脚本专题 >> javascript >> 正文

简单的ajax连接库分享

作者:佚名    责任编辑:admin    更新时间:2022-06-22

 自己写了一个简单的ajax连接库,没有使用jquery的ajax,这个代码要比jquery轻量,大家参考使用吧,

 代码如下: var ajax = {  init : function(){   var xmlHttp = new XMLHttpRequest();   if (!window.XMLHttpRequest)      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");     return xmlHttp;  },  call : function(opt){   var xmlHttp = this.init();     xmlHttp.onreadystatechange = function(){    if(xmlHttp.readyState===4)    {      xmlHttp.status===200 ?      opt.success(xmlHttp.responseText,xmlHttp.responseXML) : opt.error(xmlHttp.responseText,xmlHttp.status);    }   }   opt.data = this.parseData(opt.data);   if(opt.method.toLowerCase() === 'get'){    opt.url = opt.url + "?" + opt.data;    opt.data = null;   }   xmlHttp.open(opt.method,opt.url,opt.async);   if(opt.method.toLowerCase() === 'post')    xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");   xmlHttp.send(opt.data);  },  parseData : function(data){   if(typeof data == 'object'){    var str = '';    for(var i in data){     str += "&"+i+"="+encodeURIComponent(data[i]);    }    return str.length==0 ? str : str.substring(1);   }else{    return data;   }  } }