ajax
使用js执行异步网络请求,而不需要刷新整个页面,ajax使用XMLHttpRequest对象取得新数据
function ajax(url,fn){
const xhr=new XMLHttpRequest()
xhr.open('get',url,false)
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.state===200){
fn(shr.responseText)
}
}
xhr.send(null)
}
}
axios
axios也是基于XHR的一种封装,不过采用的是promise实现的
function axios(url){
return new Promise((resolve,reject)=>{
const xhr=new XMLHttpRequest()
xhr.open('get',url,false)
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.state==200){
resolve(JSON.stringify(xhr.responseText))
}else{
reject('error')
}
}
}
xhr.send(null)
})
}
Fetch
fetch是基于promise设计的,没有使用XMLHttpRequest对象
缺点:
1、不支持同步请求
2、只对网络请求报错,400、500会当作成功请求,需要封装处理
3、fetch默认不带cookie,需要添加配置项:fetch(url,{credentials:‘include’})
4、fetch没有办法原生检测请求的进度,而XHR可以
5、fetch不支持abort,不支持超时控制