jQuery 提供了多种方法来发送 AJAX 请求,以下是主要的几种方式:
1. $.ajax()
- 最基础的方法
$.ajax({
url: 'api/endpoint',
type: 'GET', // 或 'POST', 'PUT', 'DELETE' 等
data: { key1: 'value1', key2: 'value2' }, // 发送的数据
dataType: 'json', // 预期返回的数据类型
success: function(response) {
// 请求成功时的处理
console.log(response);
},
error: function(xhr, status, error) {
// 请求失败时的处理
console.error(error);
},
complete: function() {
// 请求完成时执行(无论成功或失败)
}
});
2. 快捷方法
$.get()
- GET 请求
$.get('api/endpoint', { param1: 'value1' }, function(response) {
// 成功回调
}, 'json');
$.post()
- POST 请求
$.post('api/endpoint', { param1: 'value1' }, function(response) {
// 成功回调
}, 'json');
$.getJSON()
- 专门获取 JSON 数据
$.getJSON('api/endpoint', function(data) {
console.log(data);
});
3. $.getScript()
- 加载并执行 JavaScript 文件
$.getScript('ajax/test.js', function() {
// 脚本加载完成后执行
});
4. 高级功能
设置全局 AJAX 默认选项
$.ajaxSetup({
timeout: 5000,
headers: {
'Authorization': 'Bearer token123'
}
});
使用 Promise 风格
$.ajax('api/endpoint')
.done(function(response) {
console.log(response);
})
.fail(function(xhr, status, error) {
console.error(error);
})
.always(function() {
console.log("请求完成");
});
5. 表单提交
使用 $.ajax()
提交表单
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(response) {
// 处理响应
}
});
});
使用 $.post()
提交表单
$('form').submit(function(e) {
e.preventDefault();
$.post($(this).attr('action'), $(this).serialize(), function(response) {
// 处理响应
});
});
注意事项
-
在现代前端开发中,原生 Fetch API 和 Axios 逐渐取代了 jQuery 的 AJAX 功能
-
确保在 DOM 加载完成后执行 jQuery 代码,可以包裹在
$(document).ready()
中 -
对于跨域请求,服务器需要正确配置 CORS 头
-
考虑添加错误处理和加载状态指示
这些方法提供了灵活的方式来与服务器交互,根据具体需求选择最适合的方式。