原生ajax请求数据五步骤
//步骤一:创建XMLHTTPRequest对象
let xhr = new XMLHttpRequest()
//步骤二:设置请求的类型,请求的url
xhr.open('get', 'https://api.github.com/search/users?q=owen')
//步骤三:发送请求
xhr.send()
xhr.timeout = 2000 //超时设置
xhr.ontimeout = ()=>{//请求超时回调}
xhr.onerror = () =>{//网络异常回调}
xhr.abort() //取消请求
//步骤四:使用事件onreadystatechange进行函数回调
xhr.onreadystatechange = function () {
//步骤五判断状态吗响应数据
if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.response)
}
}
使用fetch请求接口数据
fetch('https://api.github.com/search/users?q=owen',{
method:'',
headers:{},
body:''
}).then(res => {
/*此处fetch请求的数据需要使用res原型上对应的方法去解析
json()
blob()
arrayBuffer()
text()
formData()
*/
return res.json()
}).then(res => {
console.log('请求成功',res)
}).catch(err => {
console.log('请求错误',err)
})
axios请求接口数据
axios.get(`/gitHub/search/users?q=owen`).then(res=>{
console.log('请求成功',res)
}).catch(err=>{
console.log('请求错误',err)
})
或者
axios({
method:'', //请求方式
url:'',
headers:{}
data:{}
})