使用原生JS搭配promise来封装ajax
function ajax({ type = "GET", url = '', data = '' }) {
let p = new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
if (type == "GET" && data != undefined) {
url = url + "?" + data;
}
xhr.open(type, url);
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
resolve(this.responseText);
}
};
if (type == "POST" && data != undefined) {
xhr.send(data);
} else {
xhr.send();
}
});
return p;
}
使用方法
ajax({ url: "http://www.ujiuye.tech:3000/api/banner" }).then((data) => {
console.log(data);
}, (err) => {
console.log(err);
});