- 创建请求对象(添加 options)
- 打开一个请求(方式,URL,是否为异步)
- 配置请求头( xhr.setRequestHeader() )
- 发送请求( xhr.send(data) )
// 自己写了一个,看了下网上的大同小异
const ajax = options => {
let xhr = new XMLHttpRequest(),
opt = {},
defaultOptions = {
url: "",
method: "GET",
async: true,
data: null,
dataType: "text",
headers: {}
}
for (let key in defaultOptions) {
opt[key] = options[key] || defaultOptions[key]
}
return new Promise((resolve, reject) => {
xhr.open(opt.method, opt.url, opt.async)
for(let header in opt.headers) {
xhr.setRequestHeader(header, opt['headers'][header])
}
xhr.onreadystatechange = () => {
if (this.readyState === 4 && this.status === 200) {
resolve(this.responseText, this)
} else {
const resJson = {
code: this.status,
response: this.response
}
reject(resJson, this)
}
}
xhr.send(opt.method.toLowerCase() == 'get' ? null : xhr.data)
})
}
ajax({
url: "<https://baidu.com>"
}).then(res => {
console.log(res)
}).catch(err => {
console.error(err)
})