取消ajax请求
2019-07-16 本文已影响0人
baxiamali
取消异步请求
- 原生XHR 调用调用XHR对象的.abort()方法
var native = new XMLHttpRequest();
native.open("GET","https://api.github.com/");
native.send();
native.onreadystatechange=function(){
if(native.readyState==4&&native.status==200){
console.log(native.response);
}else{
console.log(native.status);
}
}
native.abort();
- jquery ajax
var jp = $.ajax({
type:"get",
url:"https://api.github.com/",
dataType:"json",
success:function(data){
console.log(data);
},
error:function(err){
console.log(err);
}
})
jp.abort();
- axios 特点可以同时取消
...
constructor(props) {
this.state=store.getState()
this.source = axios.CancelToken.source() //生成取消令牌用于组件卸载阻止axios请求
}
...
componentDidMount = () => {
const _t = this
const url="xxxx";
axios.get(url, {
cancelToken: _t.source.token
})
.then(res => {
...
})
.catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
console.log(thrown)
}
})
}
componentWillUnmount = () => {
//阻止请求
this.source.cancel('组件卸载,取消请求');
}
componentWillUnmount 需要做哪些操作
- 清除定时,延时函数
- 取消请求(如果请求处理代码里面有定时或者延时函数一定要取消),有一种简单的处理方法,
componentDidMount(){
this.mounted = true;
CCAjax({
url:'front/facepay/reportMeal',
headers:{token:token},
data:{
errorCode:res.resultCode
},
success:(res)=>{
if(!this.mounted) {
return
}
}
});
}
componentWillUnmount(){
this.mounted = false;
}
- 解除事件绑定