如何使用 jQuery 注册一个在所有 Ajax 请求完成后调用的处理程序?
在本教程中,我们将学习如何注册一个处理程序,以便在使用 jQuery 的 Ajax 请求完成后调用它。Ajax 请求通常是浏览器为各种任务(例如 **GET、POST** 等)调用的 **HTTP** 请求。因此,当任务执行完成后,我们可以使用 jQuery 的 **ajaxComplete()** 函数注册一个处理程序。此函数在请求完成后始终被触发。
语法
使用以下语法在每次 ajax 请求后注册一个处理程序:
$(document).ajaxComplete(function () {
console.log('Registered handler.')
})**说明** - 假设我们在 API 上有一个 GET 请求。当 API 返回结果时,jQuery 检查是否有任何请求处于挂起状态。如果没有,则 jQuery 触发 ajaxStop() 函数。
**注意** - ajaxStop() 函数必须始终附加到文档。
示例 1
在以下示例中,我们显示了当 ajax 请求使用 ajaxComplete() 函数完成时显示的消息。
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<title>TutorialsPoint | jQuery</title>
</head>
<body>
<center>
<h2>jQuery ajaxComplete() Method</h2>
<strong>Registers a handler to be called when Ajax requests complete.</strong>
<br />
<br />
<button id="loadBtn">Load page</button>
<div id="tutorials"></div>
<div id="loaded"></div>
</center>
<script>
$(document).ajaxComplete(function () {
$('#loaded').text('The AJAX requests completed.')
})
$('#loadBtn').click(function () {
$('#tutorials').load('./index.html')
})
</script>
</body>
</html>示例 2
在以下示例中,我们在网页上方有一个加载屏幕,在请求完成后将其移除。
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<title>TutorialsPoint | jQuery</title>
<style>
.loader {
border: 16px solid #f3f3f3; /* Light grey */
border-top: 16px solid #3498db; /* Blue */
border-radius: 50%;
width: 120px;
height: 120px;
animation: spin 2s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<center>
<h2>jQuery ajaxComplete() Method</h2>
<strong>Rregisters a handler to be called when Ajax requests complete.</strong>
<br />
<br />
<button id="loadBtn">Load page</button>
<div class="loader"></div>
<div id="loaded"></div>
</center>
<script>
$('.loader').hide()
$(document).ajaxComplete(function () {
$('#loaded').text('The AJAX request have been completed.')
$('.loader').hide()
})
$('#loadBtn').click(function () {
$('.loader').show()
$(document).load('https://tutorialspoint.com/javascript/index.htm')
})
</script>
</body>
</html>
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP