概览
目录
jQuery Ajax 全局事件是一组在 Ajax 请求生命周期不同阶段触发的回调函数,允许对页面上所有的 Ajax 请求进行集中监听与处理。这些事件附加到 document 元素上,涵盖了请求开始、发送、成功、完成及错误等关键节点。通过 $.ajaxSetup() 方法或直接在 $.ajax() 中设置 global: true 即可启用。同时,$.ajax() 方法提供了一系列配置选项,用以精细控制请求的各个方面,如超时、头信息、数据类型等,构成了完整 Ajax 功能的基础。
ajaxStart()
语法
$(document).ajaxStart( handler )handler:每次 Ajax 请求开始且没有其他未完成的请求时,要执行的函数。
示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ajaxStart 示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
#loader { display: none; position: fixed; top: 10px; right: 10px; background: #333; color: #fff; padding: 5px 10px; }
</style>
</head>
<body>
<div id="loader">请求中...</div>
<button id="loadData">加载数据</button>
<div id="content"></div>
<script>
$(document).ajaxStart(function() {
$('#loader').show();
});
$('#loadData').on('click', function() {
$.get('https://api.github.com/users/jquery', function(data) {
$('#content').html('用户名: ' + data.login);
});
});
</script>
</body>
</html>ajaxStop()
语法
$(document).ajaxStop( handler )handler:所有 Ajax 请求都结束后要执行的函数。
示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ajaxStop 示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
#loader { display: none; position: fixed; top: 10px; right: 10px; background: #333; color: #fff; padding: 5px 10px; }
</style>
</head>
<body>
<div id="loader">请求中...</div>
<button id="loadData">加载数据</button>
<div id="content"></div>
<script>
$(document).ajaxStart(function() {
$('#loader').show();
});
$(document).ajaxStop(function() {
$('#loader').hide();
});
$('#loadData').on('click', function() {
$.get('https://api.github.com/users/jquery', function(data) {
$('#content').html('用户名: ' + data.login);
});
});
</script>
</body>
</html>ajaxSend()
语法
$(document).ajaxSend( handler )handler:每次 Ajax 请求发送前要执行的函数,接收事件对象、jqXHR对象和包含请求设置的对象作为参数。
示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ajaxSend 示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="request1">请求 1</button>
<button id="request2">请求 2</button>
<script>
$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
jqXHR.setRequestHeader('X-Custom-Header', 'MyApp');
console.log('正在发送请求到: ' + ajaxOptions.url);
});
$('#request1').on('click', function() {
$.get('https://api.github.com/users/jquery');
});
$('#request2').on('click', function() {
$.get('https://api.github.com/users/twitter');
});
</script>
</body>
</html>ajaxSuccess()
语法
$(document).ajaxSuccess( handler )handler:每次 Ajax 请求成功完成后要执行的函数,接收事件对象、jqXHR对象和包含请求设置的对象作为参数。
示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ajaxSuccess 示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="loadData">加载数据</button>
<div id="log"></div>
<script>
$(document).ajaxSuccess(function(event, jqXHR, ajaxOptions) {
$('#log').append('<p>请求成功: ' + ajaxOptions.url + '</p>');
});
$('#loadData').on('click', function() {
$.get('https://api.github.com/users/jquery', function(data) {
console.log('数据已加载');
});
});
</script>
</body>
</html>ajaxError()
语法
$(document).ajaxError( handler )handler:每次 Ajax 请求失败后要执行的函数,接收事件对象、jqXHR对象、包含请求设置的对象以及一个描述错误类型的字符串作为参数。
示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ajaxError 示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="loadValid">加载有效数据</button>
<button id="loadInvalid">加载无效地址</button>
<div id="errorMsg" style="color: red;"></div>
<script>
$(document).ajaxError(function(event, jqXHR, ajaxOptions, thrownError) {
$('#errorMsg').text('请求 ' + ajaxOptions.url + ' 失败: ' + thrownError);
});
$('#loadValid').on('click', function() {
$.get('https://api.github.com/users/jquery');
});
$('#loadInvalid').on('click', function() {
$.get('https://api.github.com/users/non-existent-user-12345');
});
</script>
</body>
</html>ajaxComplete()
语法
$(document).ajaxComplete( handler )handler:每次 Ajax 请求完成后要执行的函数,接收事件对象、jqXHR对象和包含请求设置的对象作为参数。
示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ajaxComplete 示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="loadData">加载数据</button>
<div id="log"></div>
<script>
$(document).ajaxComplete(function() {
$('#log').append('<p>请求完成于: ' + new Date().toLocaleTimeString() + '</p>');
});
$('#loadData').on('click', function() {
$.get('https://api.github.com/users/jquery');
});
</script>
</body>
</html>$.ajaxSetup()
语法
$.ajaxSetup( settings )settings:一个对象,包含用于配置 Ajax 请求的键值对集合。
示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>$.ajaxSetup 示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="request1">请求 1</button>
<button id="request2">请求 2</button>
<script>
$.ajaxSetup({
timeout: 3000,
headers: { 'X-App-Version': '1.0' }
});
$('#request1').on('click', function() {
$.ajax({
url: 'https://api.github.com/users/jquery',
success: function() {
console.log('请求 1 成功');
}
});
});
$('#request2').on('click', function() {
$.ajax({
url: 'https://api.github.com/users/twitter',
timeout: 5000
});
});
</script>
</body>
</html>控制全局事件
语法
$.ajax({
url: '...',
global: false,
// ... 其他选项
});global:布尔值,默认为true。设置为false将阻止该请求触发ajaxStart、ajaxStop、ajaxSend、ajaxSuccess、ajaxError、ajaxComplete等全局事件。
示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>global 选项示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
#loader { display: none; }
</style>
</head>
<body>
<div id="loader">全局加载中...</div>
<button id="globalReq">触发全局事件的请求</button>
<button id="silentReq">静默请求</button>
<script>
$(document).ajaxStart(function() {
$('#loader').show();
});
$(document).ajaxStop(function() {
$('#loader').hide();
});
$('#globalReq').on('click', function() {
$.get('https://api.github.com/users/jquery');
});
$('#silentReq').on('click', function() {
$.ajax({
url: 'https://api.github.com/users/twitter',
global: false,
success: function() {
console.log('静默请求成功');
}
});
});
</script>
</body>
</html>全局事件对象
每个全局事件的处理函数都接收一系列参数,通常包括:
event:事件对象。jqXHR:jQuery XMLHttpRequest对象,是浏览器原生XMLHttpRequest的超集,包含了请求的状态和信息。ajaxOptions:包含当前请求所有设置的对象。thrownError:(仅ajaxError)当请求抛出异常时,包含错误信息。
通过这些参数,可以获取请求的 URL、类型、返回数据等细节,从而实现精细化的处理逻辑。掌握这些 jQuery Ajax 全局事件与选项,可以构建出用户体验更佳、代码更易维护的 Web 应用。这些机制提供了一种优雅的方式来处理请求的生命周期,并将横切关注点(如错误处理和加载状态)从业务逻辑中分离出来。
版本变更记录
| 版本 | 变更说明 |
|---|---|
| 1.0 | 引入基本的 Ajax 功能,包括 ajaxStart、ajaxStop、ajaxSend、ajaxSuccess、ajaxError 和 ajaxComplete 事件。 |
| 1.5 | jqXHR 对象得到增强,实现了 Promise 接口,使得全局事件返回的 jqXHR 对象更加强大。 |
| 1.8 | 不推荐使用 .ajaxStart()、.ajaxStop() 等方法的快捷方式,但事件本身依然存在。推荐使用 .on() 方法绑定这些事件。 |
| 3.0 | 更新了 Promise 兼容性,以符合 ES6 Promise 规范。jqXHR 对象的行为更接近标准 Promise。 |
| 3.5 | 进一步优化了内部事件触发机制,确保在不同场景下全局事件的稳定性和一致性。 |
浏览器兼容性
jQuery 3.x 版本致力于支持主流浏览器的最新及先前主要版本。以下为基于 jQuery 3.7.x 的浏览器兼容情况,Ajax 全局事件功能依赖于此兼容性基础。
| 浏览器类型 | 最低兼容版本 |
|---|---|
| PC 端 | |
| Chrome | 60+ (当前及先前版本) |
| Edge | 15+ (基于 Chromium) |
| Firefox | 55+ (当前及先前版本) |
| Opera | 47+ (当前及先前版本) |
| Safari | 10+ (当前及先前版本) |
| 移动端 | |
| Chrome Android | 100+ (当前版本) |
| Firefox for Android | 100+ (当前版本) |
| Opera Android | 64+ (当前版本) |
| Safari on iOS | 10+ |
| Samsung Internet | 6.2+ |
| WebView Android | 100+ (当前版本) |
| WebView on iOS | 10+ |
