一、基础语法与核心参数
$.ajax({
url: "https://api.example.com/data",
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() 替代旧版回调:
$.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:
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 数据
$.ajax({
url: "/submit",
method: "post",
contenttype: "application/json",
data: json.stringify({ email: "user@example.com" }),
datatype: "json",
})
.done(function(data) {
console.log("提交成功:", data);
});
2. 文件上传
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)
$.ajax({
url: "https://api.example.com/cross-origin",
method: "get",
xhrfields: {
withcredentials: true, // 发送 cookie
},
headers: {
"access-control-allow-origin": "*", // 服务器需配置
},
})
.done(function(data) {
console.log("跨域数据:", data);
});
4. 请求取消
const xhr = $.ajax({
url: "/long-task",
method: "get",
timeout: 5000, // 5秒超时
});
// 取消请求
settimeout(() => xhr.abort(), 3000);
五、错误处理最佳实践
$.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 等框架需要):
$.ajaxsetup({
headers: {
"x-csrftoken": csrftoken // 从 meta 标签或 cookie 中获取
}
});
2.防止 xss 攻击:
对用户输入使用 encodeuricomponent() 或 dompurify 清理。
3.https 强制:
$.ajax({
url: "https://api.example.com", // 确保协议为 https
});
七、替代方法:更简洁的 api
对于简单请求,可使用以下快捷方法:
| | |
| | |
| 方法 | 说明 |
|---|---|
| $.get() | get 请求 |
| $.post() | post 请求 |
| $.getjson() | get + jsonp |
| $.ajaxsetup() | 全局默认配置 |
// 使用 $.getjson()
$.getjson("/api/data")
.done(console.log)
.fail(console.error);
八、jquery 3.x 的重要变化
- 弃用 type 参数:改用 method。
- 默认 cache: true:get 请求默认缓存(可手动设置 cache:false)。
- **jsonp 改为 datatype: “jsonp” **:
$.ajax({
url: "https://api.example.com/data",
datatype: "jsonp",
});
九、调试技巧
1.查看网络请求:
浏览器开发者工具(f12)的 network 面板。
2.启用调试日志:
$.ajaxsetup({
debug: true // 输出详细日志到控制台
});
通过掌握以上内容,可以高效使用 $.ajax() 处理复杂的前端请求场景,同时结合现代 javascript 特性提升代码可读性和可维护性。
总结
到此这篇关于javascript中$.ajax()最新用法的文章就介绍到这了,更多相关js $.ajax()用法详解内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论