实现ajax主要分五步
1.创建XMLHttpRequest对象
2.向服务器发送请求 xhr.open(methods, url);
3.设置响应HTTP的请求状态; xhr.readyState === 4 && xhr.status === 200
4.服务器响应 xhr.responseText
5.发送请求 xhr.send()
let res = ajax(
'https://mock.presstime.cn/mock/5ff40fdd8215df0020a8eb8d/example/user',
'GET',
null,
null
)
res.then(data => {
console.log(JSON.parse(data));
})
function ajax(url, methods, body, headers) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(methods, url);
if (headers) {
for (let key in headers) {
xhr.setRequestHeader(key, headers[key])
}
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200) {
resolve(xhr.responseText)
} else {
reject(xhr)
}
}
}
xhr.send(body)
})
}