fetch 基于 Promise,语法比 XMLHttpRequest 更简洁。它返回一个 Response 对象,需要再调用 json()、text() 或 blob() 读取响应体。

本节要点

  • fetch(url) 返回 Promise,响应到达后 resolve 为 Response。
  • response.ok 为 true 时表示状态码在 200 到 299 之间。
  • response.json() 也是异步方法,需要 await 或 then。
  • fetch 只有在网络错误时 reject,HTTP 4xx/5xx 不会自动抛错。

可运行示例

用 fetch 请求 JSON,并把标题渲染成列表。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>fetch 示例</title>
</head>
<body>
  <h1>fetch</h1>
  <button id="load">加载数据</button>
  <ul id="list"></ul>

  <script>
    document.getElementById('load').addEventListener('click', () => {
      fetch('/ajax/demo/data.json')
        .then(response => {
          if (!response.ok) {
            throw new Error('HTTP ' + response.status);
          }
          return response.json();
        })
        .then(data => {
          document.getElementById('list').innerHTML =
            data.map(item => `<li>${item.title}</li>`).join('');
        })
        .catch(error => {
          document.getElementById('list').innerHTML =
            `<li>加载失败:${error.message}</li>`;
        });
    });
  </script>
</body>
</html>
运行说明:通过站点地址访问页面,点击按钮即可看到列表。把地址改成不存在的文件,可以观察 404 的处理。 在线运行示例 →

Response 的常用方法

方法用途
response.json()把响应体解析成 JSON 对象。
response.text()读取纯文本或 HTML。
response.blob()读取二进制数据,如图片、文件。
response.headers.get()读取响应头。

为什么要检查 ok

服务器返回 404 或 500 时,fetch 仍然会成功拿到 Response。如果不检查 ok,后续的 json() 可能解析失败,错误信息也不够明确。

提示:一个响应体只能读取一次。调用过 json() 后,再调用 text() 会报错。