使用原生 JavaScript 封装 ajax 可以这样做:
function ajax(method, url, data, success) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
success(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.send(data);
}
使用方式:
ajax("POST",
"/login",
"username=admin&password=123456",
function(responseText) {
console.log(responseText);
}
);
其中,method 为请求的方法(POST 或 GET),url 为请求的地址,data 为请求的数据,success 为请求成功时的回调函数。