相同的请求重复发送会影响服务器的处理速度,降低用户体验
例如
index.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 id="send">发送请求</button>
</body>
<script>
send.onclick = function() {
const x = new XMLHttpRequest();
x.open('GET', 'http://127.0.0.1:8000/send');
x.send();
x.onreadystatechange = function() {
if (x.readyState === 4)
console.log(x.response);
}
}
</script>
</html>
server.js
const express = require('express');
const app = new express();
app.get('/send', (request, response) => {
response.setHeader('Access-Control-Allow-Origin', '*');
response.send('send');
});
app.listen('8000', function() {
console.log('Listening 8000 ……');
})
多次单击发送ajax请求按钮时,浏览器会不断地向服务器发送相同的请求
解决方法:
使用标识变量,避免相同请求重复发送,更改如下:
index.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 id="send">发送请求</button>
</body>
<script>
//创建标识变量
let sendFlag = false;
send.onclick = function() {
//判断标识变量
if (sendFlag == true)
x.abort();
const x = new XMLHttpRequest();
x.open('GET', 'http://127.0.0.1:8000/send');
x.send();
sendFlag = true;
x.onreadystatechange = function() {
if (x.readyState === 4) {
console.log(x.response);
sendFlag = true;
}
}
}
</script>
</html>
此时即使多次发送相同ajax请求,浏览器会只会发送最新的请求到服务器