| 方面 | Ajax | Axios |
|---|---|---|
| 本质 | 技术思想/概念 | 具体JavaScript库 |
| API 方式 | 使用原生 XMLHttpRequest 对象 |
基于 Promise 的现代 API |
| 兼容性 | 依赖浏览器内置的 XMLHttpRequest |
支持浏览器和 Node.js |
| 请求/响应拦截 | 需手动实现 | 内置拦截器功能 |
| 自动JSON转换 | 需手动 JSON.parse() |
自动转换 JSON 数据 |
| 错误处理 | 回调函数方式 | Promise 链式调用 .catch() |
| 取消请求 | 较复杂(xhr.abort()) |
支持 CancelToken 或 AbortController |
| 跨域处理 | 需手动设置 withCredentials |
默认支持 CORS 配置 |
| 请求进度 | 通过事件监听实现 | 提供进度监控功能 |
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();
Axios
// 简洁的 Promise 语法
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
// 或使用 async/await
async function fetchData() {
try {
const response = await axios.get('https://api.example.com/data');
console.log(response.data);
} catch (error) {
console.error(error);
}
}
axios.interceptors.request.use(config => {
config.headers.Authorization = 'Bearer token';
return config;
});
axios.all() + axios.spread()timeout 参数除了 Axios,常见的 Ajax 实现库还包括:
使用 Axios 当:
使用原生 Ajax/Fetch 当:
简单来说:Ajax 是“做什么”(异步数据交互),Axios 是“怎么做”的具体工具之一。Axios 提供了更现代化、功能更完善的 API 来替代传统的 XMLHttpRequest 使用方式,是目前主流的 HTTP 客户端选择。