利用自调用匿名函数对ajax进行封装,会节省我们很多精力重复地书写代码。下面封装了get、post两种请求,以及text、xml、json数据类型传输。如下:
(function(){
//1、用于得到一个DOM元素
//定义了一个$函数 作用域有局部
var $ = function(id){
return document.getElementById(id);
};
//2、用于得到一个Ajax对象
//将$看作函数对象,init为属性,值为函数体
$.init = function(){
try{return new XMLHttpRequest()}catch(e){}
try{return new ActiveXObject(‘Microsoft.XMLHTTP‘)}catch(e){}
alert(‘请更改新浏览器!‘);
};
//用于发送Ajax get请求
$.get = function(url,data,callback,type){
var xhr = $.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);
};
//用于发送Ajax post请求
$.post = function(url,data,callback,type){
var xhr = $.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.$ = $;
})();本文出自 “做一只蜗牛真好” 博客,请务必保留此出处http://smili.blog.51cto.com/8919945/1565331
原文:http://smili.blog.51cto.com/8919945/1565331