简单封装ajax
发送一个带有参数的 post 请求
function ajax(url, method, data, successCallback, errorCallback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
successCallback(xhr.responseText);
} else {
errorCallback(xhr.statusText);
}
}
};
xhr.open(method, url, true);
if (method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
} else {
xhr.send();
}
}
使用promise封装ajax
function ajax(url, method, data) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(xhr.statusText);
}
}
};
xhr.open(method, url, true);
if (method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
} else {
xhr.send();
}
});
}
封装:$.ajax()
function ajax(url, method, data, successCallback, errorCallback) {
$.ajax({
url: url,
type: method,
data: JSON.stringify(data),
contentType: 'application/json',
success: function(response) {
successCallback(response);
},
error: function(xhr, status, error) {
errorCallback(error);
}
});
}