我知道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有什么区别?
发布评论