fetch()是推荐的原生方案但不因HTTP错误状态reject,需手动检查response.ok;默认不带cookie,无超时控制,不支持progress事件;XMLHttpRequest仍适用需细粒度控制场景;jQuery.ajax()已不推荐。
很多人写 fetch() 时以为 404 或 500 会进 catch,其实不会——fetch() 只在网络失败(如断网、DNS 错误)时 reject,HTTP 错误状态仍走 then。必须手动检查 response.ok 或 response.status:
fetch('/api/user')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(err => console.error('请求失败:', err));credentials: 'include'
AbortController 配合 signal 参数XMLHttpRequest
虽然老,但它是唯一原生支持上传/下载进度、取消请求、设置 timeout、自定义 header 的方案。比如上传大文件时监听进度:
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', e => {
if (e.lengthComputable) {
console.log(`上传中: ${(e.loaded / e.total * 100).toFixed(2)}%`);
}
});
xhr.open('POST', '/upload');
xhr.send(formData);
xhr.responseType = 'json' 可让 xhr.response 自动解析为对象,不用再 JSON.parse()
xhr.timeout = 10000 设置超时,触发 ontimeout 回调xhr.abort() 能真正中断请求(fetch() 的 AbortController 效果类似,但更复杂)jQuery 的 $.ajax() 在现代项目里基本是负优化:体积大、API 冗余、Promise 兼容性差。它的默认行为反而容易埋坑:
contentType 设为 'application/x-www-form-urlencoded',传 JSON 得手动覆盖dataType: 'json' 会在解析失败时静默吞掉错误,不如原生 response.json() 明确抛错AbortController,取消请求只能靠 xhr.abort(),但 jQuery 封装后不好拿到底层 xhr 实例自己写工具函数时,光处理 success/fail 不够,这些点常被跳过:
Content-Type:如果传了 body 且不是 FormData,自动加 headers: { 'Content-Type': 'application/json' } 并 JSON.stringify()
GET 请求自动序列化 params 到 URL(别手拼,用 URLSearchParams)cache: 'no-cache',避免 Chrome 对 GET 缓存导致数据不更新response.status 和 response.statusText,别只打印 “请求失败”浏览器兼容性上,fetch() 在 IE 完全不支持,XMLHttpRequest 从 IE5 就有。如果必须支持 IE,就别碰 fetch() —— 不是加个 polyfill 就能解决所有问题,比如 AbortController 在 IE 里根本没替代方案。