编程 告别传统 Ajax:掌握 fetch API 的简洁与强大

2025-08-15 15:50:16 +0800 CST views 605

告别传统 Ajax:掌握 fetch API 的简洁与强大

早期我们依赖 XMLHttpRequest(即 Ajax)来实现客户端与服务器的数据交换。然而,随着 Web 技术的发展,浏览器提供了更加优雅、简洁的方案——fetch API


一、传统 Ajax 的繁琐

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      var response = JSON.parse(xhr.responseText);
      console.log(response);
    } else {
      console.error('请求失败,状态码:', xhr.status);
    }
  }
};

xhr.onerror = function() {
  console.error('请求出错');
};

xhr.send();

问题:

  • 代码冗长,逻辑复杂
  • 需要处理多种状态码和事件
  • 可读性差,维护成本高

二、fetch API 的简洁之美

使用 fetch API,可以轻松完成同样的请求:

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
    return response.json();
  })
  .then(data => console.log(data))
  .catch(err => console.error('请求失败', err));

更现代的写法,结合 async/await

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
    const data = await response.json();
    console.log(data);
  } catch (err) {
    console.error('请求失败', err);
  }
}

fetchData();

逻辑清晰、代码量减少一半以上,异步代码更像同步代码。


三、fetch API 的主要特点

1. 基于 Promise

  • 可使用 .then() / .catch() 链式调用
  • 与 async/await 配合,异步代码更优雅

2. 简单的请求配置

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: '张三', age: 28 })
});

3. 灵活的响应处理

fetch 返回一个 Response 对象,可调用多种方法:

方法用途
response.json()解析为 JSON
response.text()解析为文本
response.blob()解析为 Blob
response.arrayBuffer()解析为 ArrayBuffer
response.formData()解析为 FormData

4. 支持请求中断

使用 AbortController

const controller = new AbortController();
const signal = controller.signal;

fetch('https://api.example.com/data', { signal })
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

// 中断请求
controller.abort();

5. 原生支持 CORS

  • 跨域请求无需额外封装
  • 与现代前端框架完美兼容

四、fetch API 注意事项

  1. Cookies 默认不发送
fetch('https://api.example.com/data', { credentials: 'include' });
  1. 不会自动拒绝 4xx/5xx 响应
  • 需要手动检查 response.okresponse.status
  1. 不支持直接设置超时
  • 可结合 AbortController + setTimeout 实现

五、总结

fetch API 以 简洁、灵活、现代化 的方式替代传统 Ajax:

  • 代码量更少,逻辑更清晰
  • 支持各种响应类型和中断操作
  • 与 Promise / async-await 无缝结合

在现代 Web 开发中,fetch API 已成为首选的网络请求方案,彻底告别繁琐的 Ajax 时代。

复制全文 生成海报 Web开发 JavaScript 网络请求

推荐文章

基于Flask实现后台权限管理系统
2024-11-19 09:53:09 +0800 CST
支付页面html收银台
2025-03-06 14:59:20 +0800 CST
Vue3中的自定义指令有哪些变化?
2024-11-18 07:48:06 +0800 CST
PHP中获取某个月份的天数
2024-11-18 11:28:47 +0800 CST
PHP 微信红包算法
2024-11-17 22:45:34 +0800 CST
在 Docker 中部署 Vue 开发环境
2024-11-18 15:04:41 +0800 CST
使用Vue 3实现无刷新数据加载
2024-11-18 17:48:20 +0800 CST
Grid布局的简洁性和高效性
2024-11-18 03:48:02 +0800 CST
纯CSS绘制iPhoneX的外观
2024-11-19 06:39:43 +0800 CST
向满屏的 Import 语句说再见!
2024-11-18 12:20:51 +0800 CST
小技巧vscode去除空格方法
2024-11-17 05:00:30 +0800 CST
10个极其有用的前端库
2024-11-19 09:41:20 +0800 CST
JavaScript数组 splice
2024-11-18 20:46:19 +0800 CST
宝塔面板 Nginx 服务管理命令
2024-11-18 17:26:26 +0800 CST
mysql 优化指南
2024-11-18 21:01:24 +0800 CST
nuxt.js服务端渲染框架
2024-11-17 18:20:42 +0800 CST
一个数字时钟的HTML
2024-11-19 07:46:53 +0800 CST
使用Ollama部署本地大模型
2024-11-19 10:00:55 +0800 CST
回到上次阅读位置技术实践
2025-04-19 09:47:31 +0800 CST
12个非常有用的JavaScript技巧
2024-11-19 05:36:14 +0800 CST
全栈利器 H3 框架来了!
2025-07-07 17:48:01 +0800 CST
Vue3中如何使用计算属性?
2024-11-18 10:18:12 +0800 CST
程序员茄子在线接单