Response: text() 方法

Baseline 已廣泛支援

此特性已得到良好確立,可跨多種裝置和瀏覽器版本使用。自 2017 年 3 月起,所有瀏覽器均支援此特性。

注意:此功能在 Web Workers 中可用。

text() 方法是 Response 介面的一部分,它接收一個 Response 流並將其讀取完成。它返回一個會解析為 String 的 Promise。響應總是使用 UTF-8 進行解碼。

語法

js
text()

引數

無。

返回值

一個解析為 String 的 Promise。

異常

AbortError DOMException

請求已被 中止

TypeError

因以下原因之一而丟擲:

示例

在我們 fetch text 示例(執行 fetch text 即時演示)中,我們有一個 <article> 元素和三個連結(儲存在 myLinks 陣列中)。首先,我們遍歷所有這些連結,併為每個連結設定一個 onclick 事件處理程式,以便在點選其中一個連結時執行 getData() 函式 — 並將連結的 data-page 識別符號作為引數傳遞給它。

getData() 執行時,我們使用 Request() 建構函式建立一個新請求,然後使用它來獲取一個特定的 .txt 檔案。當 fetch 成功後,我們使用 text() 方法從響應中讀取一個字串,然後將 innerText 設定為 <article> 元素的值等於文字物件。

js
const myArticle = document.querySelector("article");
const myLinks = document.querySelectorAll("ul a");

for (const link of myLinks) {
  link.onclick = (e) => {
    e.preventDefault();
    const linkData = e.target.getAttribute("data-page");
    getData(linkData);
  };
}

function getData(pageId) {
  console.log(pageId);
  const myRequest = new Request(`${pageId}.txt`);
  fetch(myRequest)
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error, status = ${response.status}`);
      }
      return response.text();
    })
    .then((text) => {
      myArticle.innerText = text;
    })
    .catch((error) => {
      myArticle.innerText = `Error: ${error.message}`;
    });
}

規範

規範
Fetch
# ref-for-dom-body-text①

瀏覽器相容性

另見