JavaScript Fetch API

定義和用法

fetch() 方法啟動從服務器獲取資源的過程。

fetch() 方法返回解析為 Response 對象的 Promise。

提示:不再需要 XMLHttpRequest。

實例

fetch(file)
.then(x => x.text())
.then(y => myDisplay(y));

親自試一試

Fetch 是基于 async 和 await 的。這個例子可能更容易理解:

async function getText(file) {
  let x = await fetch(file);
  let y = await x.text();
  myDisplay(y);
}

親自試一試

使用易于理解的名稱而不是 x 和 y:

async function getText(file) {
  let myObject = await fetch(file);
  let myText = await myObject.text();
  myDisplay(myText);
}

親自試一試

語法

fetch(file)

參數

參數 描述
file 可選。要獲取的資源的名稱。

返回值

類型 描述
Promise 解析為 Response 對象的 Promise。

Browser Support

fetch() 是 ECMAScript6 (ES6) 特性。

所有現代瀏覽器都支持 ES6 (JavaScript 2015)。

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

Internet Explorer 11(及更早版本)不支持 fetch()