一直在用fetch进行网络请求,我都知道fetch是支持Promise的,突发奇想想要自己实现一个简易版的基于Promise的的ajax;
const ajax = (method, url, data) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const upperMethod = method.toUpperCase();
xhr.open(upperMethod, url, true);
if (upperMethod === 'POST') {
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(JSON.stringify(data));
} else {
xhr.send();
}
xhr.onload = resolve;
xhr.onerror = reject;
})
}
网友评论