一、发送请求和取消发送请求
1.test.html中的内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button id="btn1">发送请求</button>
<button id="btn2">取消发送请求</button>
<script>
let btn1 = document.getElementById("btn1");
let btn2 = document.getElementById("btn2");
let xhr = null;
// 发送请求:
btn1.onclick = function () {
xhr = new XMLHttpRequest();
xhr.open("GET", "http://127.0.0.1:8000/delay");
xhr.send();
};
// 取消发送请求
btn2.onclick = function () {
xhr.abort(); //终止一个正在进行的 XMLHttpRequest(XHR)操作的方法
};
</script>
</body>
</html>
test.js中的内容:
const express = require("express");
const app = express();
app.get("/delay", (request, response) => {
response.setHeader("Access-Control-Allow-Origin", "*");
setTimeout(() => {
response.send("延时");
}, 3000);
});
app.listen(8000, () => {
console.log("服务启动,800端口监听中……");
});
2.查看浏览器的显示结果:
二、重复发送问题
【重复点击一个按钮,会发送很多请求,通过以下代码,实现只执行最后的那一个请求,多余的都取消掉,能够减轻服务器的负担】
1.test.html中的内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button id="btn">发送请求</button>
<script>
let btn = document.getElementById("btn");
let xhr = null;
//isSending用来判断是否发送了AJAX请求
let isSending = false;
btn.onclick = function () {
if (isSending) xhr.abort(); //如果之前发送过,就把之前发送的取消
xhr = new XMLHttpRequest();
xhr.open("GET", "http://127.0.0.1:8000/delay");
isSending = true;
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readystate === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
isSending = false;
}
}
};
};
</script>
</body>
</html>
test.js中的内容:
const express = require("express");
const app = express();
app.get("/delay", (request, response) => {
response.setHeader("Access-Control-Allow-Origin", "*");
setTimeout(() => {
response.send("延时");
}, 3000);
});
app.listen(8000, () => {
console.log("服务启动,800端口监听中……");
});
2.查看浏览器的显示结果:
如果有错误,欢迎大家批评指正:》
参考视频:
https://www.bilibili.com/video/BV1WC4y1b78y/?p=21&share_source=copy_web&vd_source=34d946b48e39dd850f5fb55437f0020e