Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. Response
  4. text()

Response: text() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.

Note: This feature is available inWeb Workers.

Thetext() method of theResponse interface takes aResponse stream and reads it to completion.It returns a promise that resolves with aString.The response isalways decoded using UTF-8.

Syntax

js
text()

Parameters

None.

Return value

A Promise that resolves with aString.

Exceptions

AbortErrorDOMException

The request wasaborted.

TypeError

Thrown for one of the following reasons:

Examples

In ourfetch text example (runfetch text live), we have an<article> element and three links (stored in themyLinks array.)First, we loop through all of these and give each one anonclick event handler so that thegetData() function is run — with the link'sdata-page identifier passed to it as an argument — when one of the links is clicked.

WhengetData() is run, we create a new request using theRequest() constructor, then use it to fetch a specific.txt file.When the fetch is successful, we read a string out of the response usingtext(), then set theinnerText of the<article> element equal to the text object.

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}`;    });}

Specifications

Specification
Fetch
# ref-for-dom-body-text①

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp