- 代码案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<button onclick="testGet()">发送请求</button>
<button onclick="test()">取消请求</button>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
<script>
// 2. 声明全局变量
let cancel = null;
function testGet() {
// 5. 检测上一次的请求是否已完成,未完成则取消
if(cancel !== null){
cancel()
}
axios({
method: "GET",
url: "http://localhost:3000/posts",
// 1. 添加配置对象的属性
cancelToken: new axios.CancelToken(function(c){
// 3. 将c赋值给cancel
cancel = c;
})
}).then(Response => {
console.log(Response)
// 4. 将cancel的值初始化
cancel = null;
})
}
// 点击取消按钮
function test() {
cancel();
}
</script>
</body>
</html>