1.代码
1.1前端代码
<!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 POST 请求</title>
<style>
#result {
width: 200px;
height: 100px;
border: solid 1px #90b;
}
</style>
</head>
<body>
<button>取消请求访问</button>
<div id="result"></div>
</body>
<script>
const button = document.getElementsByTagName('button')[0];
const result = document.getElementById("result");
let xhr = null;
result.addEventListener("mouseover",function () {
xhr = new XMLHttpRequest();
xhr.open("GET", "http://127.0.0.1:8000/server?"+Date.now());
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(JSON.parse(xhr.response))
} else {
}
}
};
});
button.onclick = function(){
xhr.abort();
}
</script>
</html>
2.2 服务代码
const express = require("express");
const app = express();
app.get("/server", (request, response) => {
response.setHeader("Access-Control-Allow-Origin", "*");
const data = {
name: "lixv000",
};
let str = JSON.stringify(data);
setTimeout(() => {
response.send(str);
}, 3000);
});
app.listen(8000, () => {
console.log("服务已经启动,8000端口监听中……");
});
2.代码讲解
button.onclick = function(){
xhr.abort();
}
XMLHttpRequest有一个abort方法,用于主动取消未完成的请求。