function getRequest(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('get', url, true); // true => 异步
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
resolve(xhr.responseText);
} else {
reject(xhr.responseText);
}
}
xhr.send();
});
}
function postRequest(url, data) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(xhr.responseText)
} else {
reject(xhr.responseText)
}
}
xhr.send(JSON.stringify(data));
});
}
javascript-promise封装get&&post
最新推荐文章于 2021-08-27 12:26:17 发布