ajax的封装
发布时间:2020-12-15 21:48:27 所属栏目:百科 来源:网络整理
导读:利用自调用匿名函数对ajax进行封装,会节省我们很多精力重复地书写代码。下面封装了get、post两种请求,以及text、xml、json数据类型传输。如下:(function(){//1、用于得到一个DOM元素//定义了一个$函数作用域有局部var$=function(id){returndocument.getEl
利用自调用匿名函数对ajax进行封装,会节省我们很多精力重复地书写代码。下面封装了get、post两种请求,以及text、xml、json数据类型传输。如下: (function(){ //1、用于得到一个DOM元素 //定义了一个$函数作用域有局部 var$=function(id){ returndocument.getElementById(id); }; //2、用于得到一个Ajax对象 //将$看作函数对象,init为属性,值为函数体 $.init=function(){ try{returnnewXMLHttpRequest()}catch(e){} try{returnnewActiveXObject('Microsoft.XMLHTTP')}catch(e){} alert('请更改新浏览器!'); }; //用于发送Ajaxget请求 $.get=function(url,data,callback,type){ varxhr=$.init(); if(data!=null){//传递参数、只发出请求 url=url+'?'+data; } xhr.open('get',url); xhr.setRequestHeader('If-Modified-Since','0');//解决get缓存问题 xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ //当没有指定传值类型时,默认为字符串 if(type==null){ type='text'; } //判断语句指定三种接收形式 if(type=='text'){ callback(xhr.responseText); } if(type=='xml'){ callback(xhr.responseXML); } if(type=='json'){ callback(eval("("+xhr.responseText+")")); } } }; xhr.send(null); }; //用于发送Ajaxpost请求 $.post=function(url,type){ varxhr=$.init(); xhr.open('post',url); xhr.setRequestHeader('content-type','application/x-www-form-urlencoded'); xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ //当没有指定传值类型时,默认为字符串 if(type==null){ type='text'; } //判断语句指定三种接收形式 if(type=='text'){ callback(xhr.responseText); } if(type=='xml'){ callback(xhr.responseXML); } if(type=='json'){ callback(eval("("+xhr.responseText+")")); } } }; xhr.send(data); }; //增大其作用域全局变量window方法的$属性赋值为$闭包写法 window.$=$; })(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |