Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

我们的志愿者还没有将这篇文章翻译为 中文 (简体)加入我们帮助完成翻译!

This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for the proper prefixes to use in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the spec changes.

The text() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString object (text).

Syntax

response.text().then(function (text) {
  // do something with the text response 
});

Parameters

None.

Returns

A promise that resolves with a USVString.

Example

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

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

var myArticle = document.querySelector('article');
var myLinks = document.querySelectorAll('ul a');

for(i = 0; i <= myLinks.length-1; i++) {
  myLinks[i].onclick = function(e) {
    e.preventDefault();
    var linkData = e.target.getAttribute('data-page');
    getData(linkData);
  }
};
    
function getData(pageId) {
  console.log(pageId);
  var myRequest = new Request(pageId + '.txt');
  fetch(myRequest).then(function(response) {
    return response.text().then(function(text) {
      myArticle.innerHTML = text;
    });
  });
}

Specifications

Specification Status Comment
Fetch
The definition of 'text()' in that specification.
Living Standard  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 42 [1]
 
39 (39) [2] Not supported

29 [3]

Not supported
Feature Android Firefox Mobile (Gecko) Firefox OS (Gecko) IE Phone Opera Mobile Safari Mobile Chrome for Android
Basic support Not supported Not supported Not supported Not supported Not supported Not supported Not supported

[1] Behind a preference in version 41.

[2] Behind a preference starting with version 34.

[3] Behind a preference in version 28.

See also

文档标签和贡献者

 此页面的贡献者: fscholz, Hendry, chrisdavidmills, jpmedley, kscarfone
 最后编辑者: fscholz,