問題描述
我知道 Fetch API 使用 Promise
并且它們都允許您向服務器發出 AJAX 請求.
I know that Fetch API uses Promise
s 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?
推薦答案
有些事情你可以用 fetch 而不是 XHR:
There are a few things that you can do with fetch and not with XHR:
- 您可以將緩存 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 做的事情,但它們遲早會可用(閱讀此處的未來改進"段落:https://hacks.mozilla.org/2015/03/this-api-就是這么拿取/):
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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!