如何取消Ajax中的当前请求
在本文中,我们将介绍如何取消Ajax中的当前请求。AJAX(异步JavaScript和XML)是一种用于创建快速和动态网页的技术。它允许网页在不重新加载整个页面的情况下更新其内容。
AJAX请求是使用JavaScript进行的HTTP请求,通常使用XMLHttpRequest对象或更现代的fetch() API从服务器后台检索数据,而不会中断页面的当前状态。通过AJAX请求检索到的数据可以是各种格式,包括纯文本、HTML、JSON或XML。
Ajax请求取消是指停止使用AJAX技术进行的正在进行的异步HTTP请求的过程。可以通过使用XHR(XMLHttpRequest)对象的abort()方法来实现请求的取消。abort()方法会停止请求并终止响应。这在用户发起请求但在完成之前决定取消时非常有用。例如,如果用户开始一个搜索信息的请求,但在第一个请求完成之前改变主意并决定搜索其他内容,他们可以取消第一个请求,并使用更新的信息发起一个新的请求。然而,一旦请求完成或被取消,其abort()方法将无效。
语法:
var xhr = new XMLHttpRequest();
xhr.abort();
在这里,abort()方法不接受任何参数,但是当请求中断时会返回undefined。
示例1: 在这个示例中,我们向一个示例API发送一个请求。如果我们不取消请求,API将获取数据;如果点击取消请求按钮,则请求将被取消。在这里,我们使用一些随机的URL来生成随机数据。
HTML
<!DOCTYPE html>
<html>
<head>
<meta name="viewport"
content="width=device-width,
initial-scale=1.0" />
<style>
.container {
text-align: center;
}
.btn {
cursor: pointer;
padding: 1rem;
background-color: rgb(234, 234, 72);
color: rgb(86, 5, 5);
}
.btn:active {
background-color: rgb(139, 139, 10);
}
</style>
</head>
<body>
<div class="container">
<h1 id="header"
style="color: green">
Geeksforgeeks
</h1>
<h3 id="text">
If request successful than data will
be displayed, else undefined.
</h3>
<div class="btnDiv">
<button class="btn"
onclick="requestData()">
Request Data
</button>
<button class="btn"
onclick="abortRequest()">
Abort Request
</button>
</div>
</div>
<script>
var head = document.getElementById("text");
var request = new XMLHttpRequest();
function requestData() {
request.onload = function () {
head.innerHTML = this.responseText;
};
request.open("GET", "https://...com", true);
request.send();
}
function abortRequest() {
head.innerHTML =
request.abort() +
"<br>Undefined as data is lost due to abort";
}
</script>
</body>
</html>
输出: 从输出结果来看,第一次我们请求数据成功地获取数据。但第二次在请求完成之前,我们点击了中止请求按钮,导致请求在完成之前被中止。
示例2: 这个示例使用jquery ajax请求来展示如何取消请求。在这里,我们也使用了一些随机URL来生成随机数据。
HTML
<!DOCTYPE html>
<html>
<head>
<meta name="viewport"
content="width=device-width,
initial-scale=1.0" />
<script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
</script>
<style>
.container {
text-align: center;
}
.btn {
cursor: pointer;
padding: 1rem;
background-color: rgb(234, 234, 72);
color: rgb(86, 5, 5);
}
.btn:active {
background-color: rgb(139, 139, 10);
}
</style>
</head>
<body>
<div class="container">
<h1 id="header"
style="color: green">
Geeksforgeeks
</h1>
<h3 id="text">
The request will automatically aborted
as soon as we click request data
button.
</h3>
<div class="btnDiv">
<button class="btn"
onclick="onRequest()">
Request Data
</button>
</div>
</div>
<script>
var head = document.getElementById("text");
var xhr;
function onRequest() {
//Requesting the data from api
xhr = requestData();
//aborting the request after requesting
abortRequest(xhr);
}
function requestData() {
var xhr = $.ajax({
type: "GET",
url: "https://...com",
});
return xhr;
}
function abortRequest(xhr) {
head.innerHTML =
"<br>Undefined as data is lost due to abort";
}
</script>
</body>
</html>
输出: 下面的输出显示了如何使用abort()方法取消请求的API。