$.ajax() 是 jQuery 提供的一个强大的方法,用于发送异步 HTTP 请求(比如 GET、POST),和服务器交换数据,实现页面无刷新更新。
✅ 简单理解:
$.ajax()就像一个“快递员”:
你告诉它:
- 要发往哪个地址(URL)
- 发什么数据(data)
- 用什么方式(GET/POST)
- 成功了怎么办?失败了怎么办?
它就会帮你把数据“悄悄”发给服务器,并带回结果。
🔧 基本语法
$.ajax({
url: '/api/data/', // 要请求的 URL 地址
type: 'GET', // 请求方法:GET、POST、PUT、DELETE 等
data: { name: '张三' }, // 要发送的数据(对象或字符串)
dataType: 'json', // 预期服务器返回的数据类型
success: function(response) {
// 请求成功时执行
console.log('成功:', response);
},
error: function(xhr, status, error) {
// 请求失败时执行
console.error('失败:', error);
}
});
📌 常用参数详解
| 参数 | 说明 | 示例 |
|---|---|---|
url | 请求的目标地址 | '/api/users/' |
type / method | 请求方式 | 'GET', 'POST' |
data | 要发送的数据 | { id: 1, name: '李四' } |
dataType | 预期返回的数据类型 | 'json', 'html', 'text' |
success | 成功回调函数 | function(res){ ... } |
error | 失败回调函数 | function(xhr, s, e){ ... } |
beforeSend | 发送前执行(常用于加 loading) | function(){ showLoading(); } |
complete | 请求完成(无论成功失败) | function(){ hideLoading(); } |
✅ 实际例子
1. 发送 POST 请求(如提交表单)
var postData = {
dept_ids: [101, 102],
dept_names: ['研发部', '人事部'],
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
};
$.ajax({
url: '/oa/dept/batch-import/',
type: 'POST',
data: postData,
dataType: 'json',
success: function(response) {
if (response.success) {
alert('导入成功!');
location.reload(); // 刷新页面
} else {
alert('导入失败:' + response.message);
}
},
error: function(xhr, status, error) {
console.error('请求出错:', error);
alert('网络错误,请稍后重试');
}
});
2. 发送 GET 请求(如获取数据)
$.ajax({
url: '/api/departments/',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log('获取到部门列表:', data);
// 可以在这里更新页面内容
$('#dept-list').html(data.html);
},
error: function() {
alert('加载部门列表失败');
}
});
⚠️ 注意事项
| 问题 | 解决方案 |
|---|---|
| CSRF 保护(Django) | 必须包含 csrfmiddlewaretoken 字段 |
| 跨域请求 | 需要后端支持 CORS,或使用 JSONP(仅 GET) |
| 数据类型自动转换 | 设置 dataType: 'json',jQuery 会自动 JSON.parse |
| this 指向问题 | 回调函数中 this 默认指向当前 AJAX 设置对象,可用 context: myObj 修改 |
🆚 对比其他 jQuery 方法
| 方法 | 说明 | 等价于 |
|---|---|---|
$.get() | 简化版 GET 请求 | $.ajax({ type: 'GET' }) |
$.post() | 简化版 POST 请求 | $.ajax({ type: 'POST' }) |
$.getJSON() | 专门获取 JSON 数据 | $.ajax({ dataType: 'json' }) |
例如:
// 简写
$.post('/api/save/', {name: 'test'}, function(res){
console.log(res);
});
// 等价于
$.ajax({
url: '/api/save/',
type: 'POST',
data: {name: 'test'},
success: function(res){
console.log(res);
}
});
✅ 使用场景
- 表单提交(不刷新页面)
- 动态加载数据(如下拉加载更多)
- 搜索建议(输入时实时查询)
- 点赞、收藏等交互操作
- 文件上传(配合 FormData)
💡 现代替代方案(非 jQuery)
如果你不用 jQuery,可以使用原生的 fetch():
fetch('/api/departments/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
但 $.ajax() 兼容性更好,代码更简洁,适合老项目。
✅ 总结
| 问 | 答 |
|---|---|
$.ajax() 是干什么的? | 发送异步请求,与服务器通信 |
| 常用参数有哪些? | url, type, data, success, error |
和 $.post() 有什么区别? | $.ajax() 更灵活,功能更全 |
| 必须用 jQuery 吗? | 是的,这是 jQuery 的方法 |
🎯 一句话总结:
$.ajax()是前端与后端“悄悄对话”的工具,让你在不刷新页面的情况下,发送数据、获取结果、更新界面。
269

被折叠的 条评论
为什么被折叠?



