1. <!DOCTYPE html>
    2. <html lang="zh">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>TestAjax</title>
    6. <style>
    7. #result{
    8. width: 200px;
    9. height: 100px;
    10. border: solid 1px #2a5caa;
    11. }
    12. </style>
    13. </head>
    14. <body>
    15. <button>发送请求</button>
    16. <script>
    17. const btns = document.querySelectorAll('button');
    18. let x = null;
    19. let isSending = false;// 默认为False,没有在发请求
    20. btns[0].onclick = function (){
    21. if(isSending) x.abort();// 判断请求是否在发送,若正在发送,则取消,再次创建一个新的对象
    22. x = new XMLHttpRequest();
    23. isSending = true;
    24. x.open("GET",'http://localhost:8000/cancel')
    25. x.send();
    26. x.onreadystatechange =function (){
    27. if (x.readyState === 4 ){
    28. isSending = false;
    29. }
    30. }
    31. }
    32. </script>
    33. </body>
    34. </html>