手写简易的ajax
//手写简易ajax
function ajax(url) {
const p = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { //返回完成
if (xhr.status === 200) { //成功
resolve(
JSON.parse(xhr.responseText);
)
} else if (xhr.status === 404) {
reject(new Error('404 not found'));
}
}
}
xhr.send(null);
})
return p;
}
const url = './data/test1.json';
ajax(url)
.then(res => console.log(res)) //fuifilled状态触发then回调
.catch(err => console.error(err));//rejected状态会触发catch回调