一、基础语法与核心参数
1 2 3 4 5 6 7 8 9 10 | $.ajax({ method: "GET" , // 推荐使用 method 替代 type data: { key: "value" }, dataType: "json" , headers: { "Authorization" : "Bearer token" }, success: function (response) {}, error: function (xhr, error) {}, complete: function () {}, }); |
关键参数更新说明
参数名 | 类型 | 说明 |
---|---|---|
method | String | 推荐替代 type,支持 GET, POST, PUT, DELETE 等。 |
headers | Object | 自定义请求头(如 Authorization),取代旧版 jsonp 的回调名称配置。 |
async | Boolean | 默认 true(异步),设为 false 会阻塞主线程(慎用)。 |
二、现代回调方式(Promise 风格)
jQuery 3.x 开始全面支持 Promise API,推荐使用 .done(), .fail(), .always() 替代旧版回调:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $.ajax({ url: "/api" , method: "POST" , data: JSON.stringify({ name: "John" }), }) .done( function (response) { console.log( "成功:" , response); }) .fail( function (jqXHR, textStatus) { console.error( "失败原因:" , textStatus); // "timeout", "error", "abort" }) .always( function () { console.log( "请求完成(无论成败)" ); }); |
三、异步处理与 async/await
通过将 $.ajax() 返回的 jqXHR 对象转换为 Promise,可使用 async/await:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | async function fetchData() { try { const response = await $.ajax({ url: "/api/data" , method: "GET" , dataType: "json" , }); console.log(response); } catch (error) { if (error.responseJSON) { console.error( "服务器错误:" , error.responseJSON.message); } else { console.error( "网络错误:" , error.statusText); } } } fetchData(); |
四、高级场景示例
1. 发送 JSON 数据
1 2 3 4 5 6 7 8 9 10 | $.ajax({ url: "/submit" , method: "POST" , contentType: "application/json" , data: JSON.stringify({ email: "user@example.com" }), dataType: "json" , }) .done( function (data) { console.log( "提交成功:" , data); }); |
2. 文件上传
1 2 3 4 5 6 7 8 9 10 11 12 | const formData = new FormData(document.getElementById( "uploadForm" )); $.ajax({ url: "/upload" , method: "POST" , data: formData, processData: false , // 防止 jQuery 拆分 FormData contentType: false , // 不设置 Content-Type(浏览器自动处理) }) .done( function (response) { console.log( "上传成功:" , response); }); |
3. 跨域请求(CORS)
1 2 3 4 5 6 7 8 9 10 11 12 13 | $.ajax({ method: "GET" , xhrFields: { withCredentials: true , // 发送 Cookie }, headers: { "Access-Control-Allow-Origin" : "*" , // 服务器需配置 }, }) .done( function (data) { console.log( "跨域数据:" , data); }); |
4. 请求取消
1 2 3 4 5 6 7 8 | const xhr = $.ajax({ url: "/long-task" , method: "GET" , timeout: 5000, // 5秒超时 }); // 取消请求 setTimeout(() => xhr.abort(), 3000); |
五、错误处理最佳实践
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | $.ajax({ url: "/api/data" , method: "GET" , }) .fail( function (jqXHR, textStatus, errorThrown) { switch (jqXHR.status) { case 400: console.error( "参数错误:" , jqXHR.responseJSON.errors); break ; case 401: console.error( "未授权,请登录" ); break ; case 404: console.error( "资源不存在" ); break ; default : console.error( "请求失败:" , textStatus, errorThrown); } }); |
六、安全注意事项
1.CSRF 令牌防护(Spring Security 等框架需要):
1 2 3 4 5 | $.ajaxSetup({ headers: { "X-CSRFToken" : csrfToken // 从 meta 标签或 cookie 中获取 } }); |
2.防止 XSS 攻击:
对用户输入使用 encodeURIComponent() 或 DOMPurify 清理。
3.HTTPS 强制:
1 2 3 |
七、替代方法:更简洁的 API
对于简单请求,可使用以下快捷方法:
| | |
| | |
方法 | 说明 |
---|---|
$.get() | GET 请求 |
$.post() | POST 请求 |
$.getJSON() | GET + JSONP |
$.ajaxSetup() | 全局默认配置 |
1 2 3 4 | // 使用 $.getJSON() $.getJSON( "/api/data" ) .done(console.log) .fail(console.error); |
八、jQuery 3.x 的重要变化
- 弃用 type 参数:改用 method。
- 默认 cache: true:GET 请求默认缓存(可手动设置 cache:false)。
- **jsonp 改为 dataType: “jsonp” **:
1 2 3 4 |
九、调试技巧
1.查看网络请求:
浏览器开发者工具(F12)的 Network 面板。
2.启用调试日志:
1 2 3 | $.ajaxSetup({ debug: true // 输出详细日志到控制台 }); |
通过掌握以上内容,可以高效使用 $.ajax() 处理复杂的前端请求场景,同时结合现代 JavaScript 特性提升代码可读性和可维护性。
总结
到此这篇关于JavaScript中$.ajax()最新用法的文章就介绍到这了,更多相关JS $.ajax()用法详解内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!