Ajax封装如下:
var AjaxUtil = {
get: function (url, callback) {
var xhr = createXHR();
xhr.onreadystatechange = function () {
if ((xhr.status >= 200 && xhr.status < 300) || xhr == 304) {
callback(JSON.parse(xhr.responseText));
}
}
xhr.open('get', url, ture);
xhr.send(null);
},
post: function (url, data, callback) {
var xhr = createXHR();
xhr.onreadystatechange = function () {
if ((xhr.status >= 200 && xhr.status < 300) || xhr == 304) {
callback(JSON.parse(xhr.responseText));
}
}
xhr.open('post', url, ture);
xhr.setRequsetHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
}
};
function createXHR() {
var xhr = null;
if (window.XHRHttpRequest) {
xhr = new XHRHttpRequest();
} else if (ActiveXObject) {
xhr = new ActiveXObject('Microsoft XMLHTTP');
}
return xhr;
}
(完)