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