jQuery中$.ajax方法怎么用?

$.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() 是干什么的?发送异步请求,与服务器通信
常用参数有哪些?urltypedatasuccesserror
和 $.post() 有什么区别?$.ajax() 更灵活,功能更全
必须用 jQuery 吗?是的,这是 jQuery 的方法

🎯 一句话总结

$.ajax() 是前端与后端“悄悄对话”的工具,让你在不刷新页面的情况下,发送数据、获取结果、更新界面。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一路生花工作室

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值