Fetch API和XMLHttpRequest有什么区别?

编程入门 行业动态 更新时间:2024-10-27 08:36:55
本文介绍了Fetch API和XMLHttpRequest有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道fetch正在使用promises,它们都允许你向服务器发出AJAX请求。我已经读过fetch有一些额外的功能,这些功能在XMLHttpRequest(以及fetch polyfill中,因为它基于XHR)中不可用。 fetch API有哪些额外的功能?

I know that fetch is using promises and both of them allow you to do AJAX requests to a server. I have read that fetch has some extra features, which aren't available in XMLHttpRequest (and in the fetch polyfill, since it's based on XHR). What extra capabilities does the fetch API have?

推荐答案

你可以用fetch做一些事情。不是XHR:

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

  • 您可以将Cache API与请求和响应对象一起使用;
  • 您可以执行 no-cors 请求,从未实现CORS的服务器获取响应。您无法直接从JavaScript访问响应主体,但您可以将其与其他API一起使用(例如,缓存API);
  • 流式响应(使用XHR,整个响应缓冲在内存中) ,使用fetch,您将能够访问低级别流)。这在所有浏览器中都不可用,但很快就会推出。
  • 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做一些事情你还不能用fetch做,但它们迟早会被提供(请阅读这里的未来改进段落: hacks.mozilla/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: hacks.mozilla/2015/03/this-api-is-so-fetching/):

  • 中止请求(现在可以在Firefox和Edge中使用,正如@sideshowbarker在他的评论中解释的那样);
  • 报告进度。

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

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

更多推荐

Fetch API和XMLHttpRequest有什么区别?

本文发布于:2023-11-24 19:02:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626449.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   Fetch   API   XMLHttpRequest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!