微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ajax的封装

利用自调用匿名函数对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.$=$;
})();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐