ajax 简单封装, 支持 get post
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 = new XMLHttpRequest();
obj.data = params(obj.data);
if(obj.method.toUpperCase() === '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.toUpperCase() === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(obj.data);
} else {
xhr.send(null);
}
function callback() {
if(xhr.status == 200) {
obj.success(xhr.responseText);
} else {
alert('error');
}
}
}
div.onclick = function() {
ajax({
url: 'http://localhost:8080/webApi/list.do',
method: 'post',
data: {
'pageCount': '10',
'pageNow': '1'
},
success: function(text) {
var jsonData = JSON.parse(text);
alert(text);
},
async: true
});
};