js方法写一个ajax请求,通过return一个promise来接受data数据
function Ajax(type, url, boolean) {
//type请求方式, url:请求路径, boolean:布尔值, true: 异步, false: 同步
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open(type, url, boolean)
xhr.setRequestHeader('content-Type', 'application/x-www-form-urlencoded')
//通常post请求需要设置请求头信息
xhr.send()
//send 里可以接一个形参,用作发送请求时传递参数
xhr.onreadystatechange = function () {
if (xhr.status == 200 && xhr.readyState == 4) {
let data = JSON.parse(xhr.responseText)
resolve(data)
}
}
})
}
Ajax('get', ' https://cnodejs.org/api/v1//topics', true).then(res => {
console.log(res)
})