Javascirpt提高:采用 Promise、Fetch、Axios、XHR、jQuery AJAX 等不同技术访问Web Api数据接口的代码示例-由Deepseek产生
在访问 Web API 时,不同的技术提供了不同的语法、默认行为、错误处理机制以及浏览器兼容性。下面分别给出示例(以 GET 请求为例,并附带 POST 请求的简单对比),并总结它们的主要区别。
·
在访问 Web API 时,不同的技术提供了不同的语法、默认行为、错误处理机制以及浏览器兼容性。下面分别给出示例(以 GET 请求为例,并附带 POST 请求的简单对比),并总结它们的主要区别。
1. Promise(原生 Promise 包装)
Promise 本身不是发起请求的工具,而是异步编程模式。任何发起请求的方法(如 XHR、Fetch)都可以用 Promise 封装,以便链式调用和统一错误处理。
示例:将 XHR 封装为 Promise 函数。
function get(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(new Error(xhr.statusText));
}
};
xhr.onerror = () => reject(new Error('Network error'));
xhr.send();
});
}
// 使用
get('https://api.example.com/data')
.then(data => console.log(data))
.catch(error => console.error(error));
特点:
- 需要手动封装 XHR 或利用其他 API
- 解决了回调地狱,但仍需手动处理 JSON 解析、状态码等
2. Fetch API(原生)
Fetch 是现代浏览器内置的 API,返回一个 Promise,语法简洁,但默认不拒绝 HTTP 错误状态(如 404、500),需要手动检查 response.ok。
// GET 请求
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // 返回 Promise,解析 JSON
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
// POST 请求
fetch('https://api.example.com/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'John' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
特点:
- 基于 Promise,原生支持,无需额外库
- 不会自动转换 JSON,需调用
response.json() - 默认不带 Cookie,需配置
credentials: 'include' - 网络错误(如断网)会触发 reject,但 HTTP 状态码(如 404)不触发 reject
3. Axios(第三方库)
Axios 是一个基于 Promise 的 HTTP 客户端,支持浏览器和 Node.js。它自动转换 JSON,提供了更丰富的功能(如请求/响应拦截器、取消请求、超时设置等)。
// GET 请求
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data); // 数据自动放在 data 属性中
})
.catch(error => {
if (error.response) {
// 请求已发出,但服务器返回状态码非 2xx
console.error(error.response.status, error.response.data);
} else {
// 网络错误或其他
console.error(error.message);
}
});
// POST 请求
axios.post('https://api.example.com/data', { name: 'John' })
.then(response => console.log(response.data))
.catch(error => console.error(error));
特点:
- 自动转换 JSON 数据
- 响应对象包含
data、status、headers等 - 对 HTTP 错误状态(4xx、5xx)会 reject Promise,便于统一处理
- 支持取消请求、超时、拦截器等功能
4. XHR(XMLHttpRequest)
XMLHttpRequest 是传统原生方式,基于回调,代码较冗长,但兼容性最好(包括 IE)。
// GET 请求
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(JSON.parse(xhr.responseText));
} else {
console.error('Request failed:', xhr.status);
}
}
};
xhr.onerror = function() {
console.error('Network error');
};
xhr.send();
// POST 请求
const xhrPost = new XMLHttpRequest();
xhrPost.open('POST', 'https://api.example.com/data');
xhrPost.setRequestHeader('Content-Type', 'application/json');
xhrPost.onload = function() {
if (xhrPost.status === 200) {
console.log(JSON.parse(xhrPost.responseText));
}
};
xhrPost.send(JSON.stringify({ name: 'John' }));
特点:
- 历史悠久,兼容所有浏览器
- 需要手动处理状态码、JSON 解析
- 不支持 Promise,容易陷入回调地狱,但可通过封装改进
5. jQuery AJAX($.ajax)
jQuery 的 $.ajax 方法提供了简化的跨浏览器 API,返回一个 jqXHR 对象,该对象实现了 Promise 接口(.then、.done、.fail、.always)。
// GET 请求
$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
dataType: 'json', // 自动解析 JSON
success: function(data) {
console.log(data);
},
error: function(xhr, status, error) {
console.error(error);
}
});
// 使用 Promise 风格
$.ajax({
url: 'https://api.example.com/data',
method: 'GET'
})
.then(data => console.log(data))
.fail(error => console.error(error));
// POST 请求
$.ajax({
url: 'https://api.example.com/data',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ name: 'John' }),
dataType: 'json'
})
.done(data => console.log(data));
特点:
- 依赖 jQuery 库
- 自动根据
dataType解析响应(如 JSON) - 支持传统回调(success、error)和 Promise 风格(done、fail)
- 内置许多默认设置(如跨域、超时等)
主要区别对比
| 技术 | 异步处理 | 自动 JSON 解析 | 错误状态码处理 | 浏览器兼容性 | 依赖 |
|---|---|---|---|---|---|
| Promise + XHR | Promise | 手动 | 需手动判断状态码 | 所有(需封装) | 无 |
| Fetch | Promise | 手动调用 .json() |
HTTP 错误不 reject,需手动判断 response.ok |
现代浏览器,IE 不支持 | 无 |
| Axios | Promise | ✅ 自动 | 4xx/5xx 自动 reject | 主流浏览器 + Node.js | 需要安装 |
| XHR | 回调 | 手动 | 需手动判断状态码 | 所有 | 无 |
| jQuery AJAX | 回调/Promise | ✅ 自动(配置 dataType) |
可通过 error 回调处理 | 所有(需 jQuery) | jQuery 库 |
选择建议:
- 现代项目推荐 Fetch(原生)或 Axios(功能更强大)。
- 需要兼容老旧浏览器(如 IE)时,可用 XHR 或 jQuery AJAX。
- 已有 jQuery 项目可直接使用
$.ajax,避免额外依赖。
更多推荐



所有评论(0)