不再考虑浏览器兼容问题,可以放弃任何ajax封装方法;
因为这是自带的,无论你使用与否,浏览器都会把它放到window对象当中
对于那些对网页性能要求极高的前段工作者们,是绝对不会允许自己的代码中引入不必要的代码
传统AJAX已死,Fetch永生,不推荐使用第三方库,例如 axios

mdn fetch文档
https://developer.mozilla.org/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/fetch

fetch特点

  1. 语法简洁,更加语义化
  2. 基于标准 Promise 实现,支持 async/await
  3. 同构方便,使用 isomorphic-fetch

fetch的兼容性

  1. 由于 IE8 是 ES3,需要引入 ES5 的 polyfill: es5-shim, es5-sham
  2. 引入 Promise 的 polyfill: es6-promise
  3. 引入 fetch 探测库:fetch-detector
  4. 引入 fetch 的 polyfill: fetch-ie8
  5. 可选:如果你还使用了 jsonp,引入 fetch-jsonp
  6. 可选:开启 Babel 的 runtime 模式,现在就使用 async/await

fetch的缺点

  • 不能提供上传的进度
  • 不能 控制超时时间
  • 不能 abort中断请求

fetch的用法

  1. fetch('https://api.github.com/users/chriscoyier/repos')
  2. .then(response => response.json())
  3. .then(data => {
  4. // data就是我们请求返回的数据
  5. console.log(data)
  6. })

fetch的第二个参数为一个对象

  1. fetch(url, params)
  2. // params
  3. {
  4. method: 'POST',
  5. headers: {
  6. 'Content-Type': 'application/json'
  7. },
  8. credentials: 'include',
  9. body: JSON.stringify(content)
  10. }

fetch完成用法

  1. fetch('url', {data: {}, method: '', body: '{}', headers})
  2. .then(response => {
  3. if (response.ok) {
  4. return response.json()
  5. } else {
  6. return Promise.reject('something went wrong!')
  7. }
  8. })
  9. .then(data => console.log('data is', data))
  10. .catch(error => console.log('error is', error))

new Request

  1. const req = new Request('/api/list', {
  2. method: 'POST',
  3. headers: {
  4. 'Content-Type': 'application/json'
  5. },
  6. credentials: 'include',
  7. body: JSON.stringify(content)
  8. })
  9. fetch(req).then(res => res.json())
  10. .then(res => console.log(res))

fetch报错

fetch.jpg