提取API与XMLHttpRequest [英] Fetch API vs XMLHttpRequest

查看:58
本文介绍了提取API与XMLHttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Fetch API使用 Promise s,它们都允许您向服务器发送AJAX请求。

I know that Fetch API uses Promises and both of them allow you to do AJAX requests to a server.

我已阅读到Fetch API具有一些额外的功能,这些功能在 XMLHttpRequest (以及Fetch API polyfill中不可用,因为它基于 XHR )。

I have read that Fetch API has some extra features, which aren't available in XMLHttpRequest (and in the Fetch API polyfill, since it's based on XHR).

Fetch API有哪些额外功能?

What extra capabilities does the Fetch API have?

推荐答案

您可以通过获取而不是XHR来做一些事情:

There are a few things that you can do with fetch and not with XHR:


  • 您可以将Cache API与请求和响应对象一起使用;

  • 您可以执行 no-cors 请求,从服务器获取响应没有实现CORS。您不能直接从JavaScript访问响应主体,但是可以将其与其他API(例如Cache API)一起使用;

  • 流式响应(使用XHR,整个响应都缓存在内存中,通过提取,您将可以访问低级流。并非所有浏览器都提供此功能,但很快就会提供。

  • You can use the Cache API with the request and response objects;
  • You can perform no-cors requests, getting a response from a server that doesn't implement CORS. You can't access the response body directly from JavaScript, but you can use it with other APIs (e.g. the Cache API);
  • Streaming responses (with XHR the entire response is buffered in memory, with fetch you will be able to access the low-level stream). This isn't available yet in all browsers, but will be soon.

您可以使用XHR进行以下操作您尚无法使用获取功能,但它们迟早会可用(请在此处阅读未来的改进部分: https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/ ):

There are a couple of things that you can do with XHR that you can't do yet with fetch, but they're going to be available sooner or later (read the "Future improvements" paragraph here: https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/):


  • 中止请求(现在可以在Firefox和Edge中使用,如@sideshowbarker在评论中所述);

  • 报告进度。

本文 https://jakearchibald.com/2015/thats-so-fetch/ 包含更详细的说明。

This article https://jakearchibald.com/2015/thats-so-fetch/ contains a more detailed description.

这篇关于提取API与XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆