【译】XMLHttpRequest和Fetch, 谁最适合AJAX?

2022-10-12,,,

原文地址:

目录

  • ajax到ajax
  • xmlhttprequest
  • fetch
    • 默认无cookie
    • 中止fetch
    • 没有progress
  • xmlhttprequest vs fetch?

2019年是ajax诞生的20周年。可以说,xmlhttprequest的第一次实现是在1999年作为ie5.0 activex组件发布。

在此之前,曾经有一些方法可以在不刷新页面的情况下从服务器获取数据,但是他们通常依赖笨拙的技术,例如<script>注入或第三方插件。微软开发了xmlhttprequest初始版本, 用于替代outlook基于浏览器的电子邮件客户端。

xmlhttprequest直到2006年才成为web标准,但在此之前已在大多数浏览器中被实现。由于它在gmail和google maps中的采用,jesse james garrett在2005年发表了一篇文章:ajax: a new approach to web applications.这个新术语吸引了开发人员的关注。

从ajax到ajax

ajax是asynchronous javascript and xml的简称。"asynchronous"一词很明显,但是:

  1. 虽然vbscript和flash也可以实现,但是javascript更合适
  2. 有效负载不必是xml,尽管在当时很流行。在今天,可以使用任何的数据格式,通常json是首选。

现在,我们将“ajax”用作客户端从服务器获取数据并动态更新dom,而无需刷新整个页面的通用术语。ajax是大多数web应用程序和单页应用程序(spa)的核心技术。

xmlhttprequest

以下javascript代码展示了如何使用xmlhttprequest(通常简称为xhr)向http://domain/service发出的http get请求。

let xhr = new xmlhttprequest();
xhr.open('get', 'http://domain/service');

// request state change event
xhr.onreadystatechange = function() {
  // request completed?
  if (xhr.readystate !== 4) return;

  if (xhr.status === 200) {
    // request successful - show response
    console.log(xhr.responsetext);
  } else {
    // request error
    console.log('http error', xhr.status, xhr.statustext);
  }
};

// start request
xhr.send();

xmlhttprequest对象有许多属性、方法和事件。例如,可以设置和监测以毫秒为单位的超时:

// set timeout
xhr.timeout = 3000; // 3 seconds
xhr.ontimeout = () => console.log('timeout', xhr.responseurl);

并且progress事件可以报告长时间运行的文件上传:

// upload progress
xhr.upload.onprogress = p => {
  console.log( math.round((p.loaded / p.total) * 100) + '%') ;
}

属性的数量可能令人困惑,而且xmlhttprequest的早期实现在跨浏览器之间也不一致。因此,很多库和框架都提供了ajax的封装函数,例如jquery.ajax()方法:

// jquery ajax
$.ajax('http://domain/service')
  .done(data => console.log(data))
  .fail((xhr, status) => console.log('error:', status));

fetch

fetch api是xmlhttprequest的现代替代方案。通用的header,request和response接口提供了一致性,同时promises允许更简单的的链式调用和不需要回调的async/await。

fetch(
    'http://domain/service',
    { method: 'get' }
  )
  .then( response => response.json() )
  .then( json => console.log(json) )
  .catch( error => console.error('error:', error) );

fetch简洁,优雅,易于理解,并且在pwa service worker中大量使用。为什么不用它替代古老的xmlhttprequest呢?

不幸的是,web开发从未如此明确。fetch还不是用于ajax的完美替代品...

浏览器支持

fetch api在大部分浏览器中得到了很好的,但是不支持所有版本的ie。使用2017年之前版本的chrome,firefox和safari的人可能也会遇到问题。这些用户或许只占你用户群的一小部分……也有可能是主要客户。所以编码之前,请务必确认兼容性!

此外,与成熟的xhr对象相比,fetch api较新,并且会接收更多正在进行的更新。这些更新不太可能破坏原始代码,但预计未来几年会进行一定的维护工作。

默认无cookie

xmlhttprequest不同,fetch并不会默认发送cookie,因此应用的身份验证可能会失败。可以通过更改第二个参数中传递的初始值来解决此问题,例如:

fetch(
  'http://domain/service',
  {
    method: 'get',
    credentials: 'same-origin'
  }
)

错误不会被拒绝

令人惊讶的是,http错误(例如404 page not found500 internal server error)不会导致fetch返回的promise标记为reject;.catch()也不会被执行。想要精确的判断 fetch是否成功,需要包含 promise resolved 的情况,此时再判断 response.ok是不是为 true。如下:

fetch(
    'http://domain/service', 
    { method: 'get' }
  )
  .then( response => {
    if(response.ok) {
      return response.json();
    }
    throw new error('network response was not ok.');
  })
  .then( json => console.log(json) )
  .catch( error => console.error('error:', error) );

仅当请求无法完成时才触发reject,例如网络故障或请求被阻止。这会使错误捕获更加复杂。

不支持超时

fetch不支持超时,只要浏览器允许,请求将继续。解决方法是可以将fetch包装在一个promise中,例如:

// fetch with a timeout
function fetchtimeout(url, init, timeout = 3000) {
  return new promise((resolve, reject) => {
    fetch(url, init)
      .then(resolve)
      .catch(reject);
    settimeout(reject, timeout);
  }
}

或使用promise.race()决定fetch或timeout何时首先完成,例如:

promise.race([
  fetch('http://url', { method: 'get' }),
  new promise(resolve => settimeout(resolve, 3000))
])
  .then(response => console.log(response))

中止fetch

通过xhr.abort()很容易结束一个xhr请求,另外也可以通过xhr.onabort函数监测事件解决。

之前一直无法中止一个fetch请求,但是现在实现了abortcontroller api的浏览器可以支持它。这将触发一个信号,该信号可以传递给fetch启动对象:

const controller = new abortcontroller();

fetch(
  'http://domain/service',
  {
    method: 'get'
    signal: controller.signal
  })
  .then( response => response.json() )
  .then( json => console.log(json) )
  .catch( error => console.error('error:', error) );

fetch可以通过调用controller.abort()来中止。promise被标记reject后,会调用.catch()函数。

没有progress

在撰写本文时,fetch仍不支持进度事件。因此,不可能显示文件上传或大型表单提交的进度状态。

xmlhttprequest vs fetch?

最后,选择还是看你自己……除非你的应用是要求有上传进度条的ie客户端。你也可以选择将fetch polyfill与promise polyfill结合使用,以便在ie中执行fetch代码。

对于更简单的ajax调用,xmlhttprequest是低级别的,更复杂的,并且你需要封装函数。不幸的是,一旦你开始考虑超时,中止调用和错误捕获的复杂性,fetch也会如此。

fetch的未来可期。但是,该api是相对较新,它不提供所有xhr的功能,并且某些参数设置比较繁琐。因此在以后的使用过程中,请注意上述问题。

《【译】XMLHttpRequest和Fetch, 谁最适合AJAX?.doc》

下载本文的Word格式文档,以方便收藏与打印。