重复的相同请求会让服务器压力很大,所以在发送请求前,要判断之前有没有过该请求,如果有,则终止上次该请求
<!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>发送请求</button>
<script>
const btns = document.getElementsByTagName('button');
let xhr = null;
let isSending = false;
btns[0].onclick = function(){
if(isSending)
xhr.abort();
xhr = new XMLHttpRequest();
isSending = true;
xhr.open('get','http://127.0.0.1:8000/delay');
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
isSending = false;
}
}
}
</script>
</body>
</html>