//添加事件处理
function addEvent(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
} else if (obj.attachEvent) {
obj.attachEvent(‘on‘ + type, function () {
fn.call(obj);
});
}
}
//移除事件处理
function removeEvent(obj, type, fn) {
if (obj.removeEventListener) {
obj.removeEventListener(type, fn, false);
} else if (obj.detachEvent) {
obj.detachEvent(‘on‘ + type, fn);
}
}
//封装ajax
function createXHR(){
if(XMLHttpRequest){
return new XMLHttpRequest();
}else{
return new ActiveXObject(‘Microsoft.XMLHTTP‘);
}
}
//名值对转换为字符串
function params(data){
var arr = [];
for(var i in data){
arr.push(encodeURIComponent(i) + ‘=‘ + encodeURIComponent(data[i]));
}
return arr.join(‘&‘);
}
function ajax(obj){
var xhr = createXHR();
obj.method = obj.method.toUpperCase()
obj.url = obj.url + ‘?rand=‘ + Math.random();
obj.data = params(obj.data);
if(obj.method === ‘GET‘){
obj.url += obj.url.indexOf(‘?‘) == -1? ‘?‘ + obj.data : ‘&‘ + obj.data;
}
if(obj.async === true){
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
callback();
}
};
}
xhr.open(obj.method,obj.url,obj.async);
if(obj.method === "POST"){
xhr.setRequestHeader(‘Content-Type‘,‘application/x-www-form-urlencoded‘);
xhr.send(obj.data);
}else{
xhr.send(null);
}
if(obj.async === false){
callback();
}
function callback(){
if(xhr.status == 200){
obj.success(xhr.responseText);
}else{
alert(‘获取数据错误!错误代码:‘ + xhr.status + ‘,错误信息:‘ . xhr.statusText);
}
}
}
//调用ajax
addEvent(document,‘click‘,function(){
ajax({
method: ‘get‘,
url: ‘demo.php‘,
data: {
‘name‘: ‘lee‘
},
success: function(text){
var result = JSON.parse(text);
},
async: true
});
});