AJAX 如何取消XMLHttpRequest请求
在本文中,我们将学习如何停止或取消已经发送到服务器的HTTP请求。
XMLHttpRequest 是一个我们用来向服务器发送HTTP请求以获取所需的数据的对象。
XMLHttpRequest 提供了一个 abort() 方法来取消已发送到服务器的请求。
XMLHttpRequest.abort()方法: 该方法用于中止或取消HTTP请求。它会将请求的 readyState 更改为 0 ,这意味着状态未初始化,并且请求不会进一步处理。
语法:
var request = new XMLHttpRequest();
request.abort();
注意: abort() 方法不接受任何参数,但在请求中止时会返回 undefined 任何值 。
示例:
HTML
<!DOCTYPE html>
<html>
<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">
<style>
#container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
}
#btnDiv {
width: 20vw;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-around;
}
.btn {
cursor: pointer;
}
</style>
</head>
<body>
<div id="container">
<h2 id="heading" style="color:green;">
GeeksforGeeks
</h2>
<div id="btnDiv">
<button class="btn" onclick="requestData()">
Request Data
</button>
<button class="btn" onclick="abortRequest()">
Abort Request
</button>
</div>
</div>
<script>
var head = document.getElementById('heading');
var request = new XMLHttpRequest();
function requestData() {
request.onload = function () {
head.innerHTML = this.responseText;
}
request.open('GET', 'gfgInfo.txt', true);
request.send();
}
function abortRequest() {
head.innerHTML = request.abort() +
"<br>It shows undefined, as the data"
+ " is lost on aborting request.";
}
</script>
</body>
</html>
输出:

浏览器支持:
- Chrome
- Firefox
- Opera
- Safari
- Edge
- Internet Explorer
极客教程