原生Javascript封装的一个AJAX函数分享
最近的工作中涉及到大量的ajax操作,本来该后台做的事也要我来做了.而现在使用的ajax函数是一个后台人员封装的—-但他又是基于jquery的ajax,所以离开了jquery这个函数就毫无作用了.而且我觉得,jquery的ajax方法是很完善的了,可以直接用,如果都有jquery了,那么他的ajax就不用白不用了.我缺少的是一个能在没有jquery的情况下使用的ajax方法.
所以我也花一天时间写了一个,参数与调用方法类似于jquery的ajax.就叫xhr吧,因为xhr=XMLHttpRequest.
/*
*Name:xhr,AJAX封装函数
*Description:一个ajax调用封装类,仿jquery的ajax调用方式
*Author:十年灯
*/
varxhr=function(){
var
ajax=function (){
return('XMLHttpRequest'inwindow)?function (){
returnnewXMLHttpRequest();
}:function (){
returnnewActiveXObject("Microsoft.XMLHTTP");
}
}(),
formatData=function(fd){
varres='';
for(varfinfd){
res+=f+'='+fd[f]+'&';
}
returnres.slice(0,-1);
},
AJAX=function(ops){
var
root=this,
req=ajax();
root.url=ops.url; root.type=ops.type||'responseText'; root.method=ops.method||'GET'; root.async=ops.async||true; root.data=ops.data||{}; root.complete=ops.complete||function (){}; root.success=ops.success||function(){}; root.error= ops.error||function(s){alert(root.url+'->status:'+s+'error!')}; root.abort=req.abort; root.setData=function (data){ for(vardindata){ root.data[d]=data[d]; } } root.send=function (){ vardatastring=formatData(root.data), sendstring,get=false, async=root.async, complete=root.complete, method=root.method, type=root.type; if(method==='GET'){ root.url+='?'+datastring; get=true; } req.open(method,root.url,async); if(!get){ req.setRequestHeader("Content-type","application/x-www-form-urlencoded"); sendstring=datastring; }
//在send之前重置onreadystatechange方法,否则会出现新的同步请求会执行两次成功回调(chrome等在同步请求时也会执行onreadystatechange) req.onreadystatechange=async?function (){ //console.log('asynctrue'); if(req.readyState==4){ complete(); if(req.status==200){ root.success(req[type]); }else{ root.error(req.status); } } }:null; req.send(sendstring); if(!async){ //console.log('asyncfalse'); complete(); root.success(req[type]); } } root.url&&root.send(); }; returnfunction(ops){returnnewAJAX(ops);} }();