效果展示:
功能:
点击发送请求,如果之前还有请求还没停止,则取消上一个请求,发送新的请求,减轻服务器压力
HTML和JS代码如下:
<!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>ajax 取消重复请求</title>
</head>
<body>
<button>发送请求</button>
<button>取消请求</button>
<script>
// 获取元素
const btn = document.querySelectorAll('button');
let xhr = null;
// 标识变量
let isSending = false;
// 绑定事件
btn[0].onclick = function() {
// 判断是否正在发送中
if(isSending) xhr.abort();
// 1.创建对象
xhr = new XMLHttpRequest();
isSending = true;
// 2.初始化 设置请求方法和url
xhr.open('GET','http://127.0.0.1:8000/delay');
// 3.发送
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
// 修改标识变量
isSending = false;
}
}
}
btn[1].onclick = function() {
xhr.abort();
}
</script>
</body>
</html>
// 引入
const { request } = require('express');
// 创建应用对象
const express = require('express');
// 创建应用对象
const app = express();
// 创建路由规则
app.get('/server',(request,response) => {
// 设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
// 设置响应体
response.send('hello ajax~~');
});
app.get('/delay',(request,response) => {
// 设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
setTimeout(() => {
// 设置响应体
response.send('hello ajax~~');
}, 3000);
});
// 监听端口启动服务
app.listen(8000,() => {
console.log("服务已启动,8000端口监听中...");
})