Fetch API AJAX

浏览器兼容性

caniuse

支持检查

if (typeof fetch === 'function' && typeof window.fetch === 'function') {
  // 支持
}

if (typeof fetch !== 'function' || typeof window.fetch !== 'function') {
  // 不支持
}

示例代码

var req = new Request('/data.json', { method: 'POST', cache: 'reload' });
fetch(req)
  .then(function (res) {
    return res.json();
  })
  .then(function (data) {
    console.log(data);
  });

credentials 凭证参数

fetch('a.com/api', { credentials: 'include' }).then(function (res) {
  // ...
});

var req = new Request('/data.json', { method: 'POST', cache: 'reload', credentials: 'include' });
fetch(req)
  .then(function (res) {
    return res.json();
  })
  .then(function (data) {
    console.log(data);
  });

参考资料

在 GitHub 上编辑本页面 更新时间: Mon, Apr 10, 2023