使用abort方法
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>取消ajax请求</title>
</head>
<body>
<button>发送请求</button>
<button>取消请求</button>
</body>
<script>
const btns = document.querySelectorAll('button');
let x = null;
btns[0].onclick = function() {
x = new XMLHttpRequest();
x.open('GET', 'http://127.0.0.1:8000/cancle')
x.send();
}
btns[1].onclick = function() {
console.log('cancle');
x.abort();
}
</script>
</html>
server.js
const express = require('express');
const app = new express();
app.get('/cancle', (request, response) => {
response.setHeader('Access-Control-Allow-Origin', '*');
response.send('请求成功');
});
app.listen('8000', function() {
console.log('listening 8000 port……');
});
运行结果
备注:由于访问本机接口时间过短,手动更改网络的属性才可以测试取消效果。