axios取消请求方法一
let send_btn = document.getElementById("send_btn") //发送请求按钮
let cancel_btn = document.getElementById("cancel_btn") //取消请求按钮
let cancel = null;
send_btn.onclick = function(){
if(cancel != null){
cancel() //如果上一次的请求还在继续,则取消
}
axios({
method:"get",
url:"http://localhost:3000/test.php",
cancelToken:new axios.CancelToken(function(c){
cancel = c
})
}).then(response=>{
//处理响应数据
cancel = null
}).catch(reason=>{
//错误处理
})
}
cancel_btn.onclick = function(){
//取消请求
cancel()
}
axios取消请求方法二
//利用source对象创建canceltoken
let send_btn = document.getElementById("send_btn") //发送请求按钮
let cancel_btn = document.getElementById("cancel_btn") //取消请求按钮
let source = axios.CancelToken.source();
send_btn.onclick = function(){
// 判断上一次的请求是否还在继续,如果还在继续,则取消上一次的请求
if(source.token._listeners!=undefined )
{
source.cancel("取消请求")
source = axios.CancelToken.source()
}
axios.get('http://localhost:3000/front-end/axios/response.php',{
cancelToken:source.token
}).then(response=>{
// 处理响应
}).catch(reason=>{
if(axios.isCancel(reason)){
console.log("取消请求",reason)
}else{
//错误处理
}
})
}
//取消按钮点击,则取消请求
cancel_btn.onclick = function(){
source.cancel("请求已被取消")
source = axios.CancelToken.source()
}