Body.text()

翻译不完整。 请帮助我们翻译这篇文章!

Body mixin 的 text() 方法提供了一个可供读取的“返回流”(Response stream),并将它读取完。它返回一个包含 USVString 对象(也就是文本)的 Promise 对象,返回结果的编码永远是 UTF-8。

语法

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

参数

无。

返回值

A promise that resolves with a USVString.

示例

在我们 fetch text example (运行 fetch text live)的案例中, 我们有一个 <article> 元素和三个链接(储存在 myLinks 数组中),首先,遍历 myLinks 数组,并且给数组中的所有元素添加 onclick 事件监听器,当按钮被点击的时候,链接的 data-page 标识作为会参数传入 getData() 中。

当进入 getData() 函数, 我们使用 Request() 构造函数创建了一个请求(Request)对象,然后,使用它获取指定的.txt的文件, 当fetch 函数执行成功, 我们使用 text() 函数来返回一个USVString (text) 对象,将它设置到 <article> 对象的innerHTML (元素文本)中。

const myArticle = document.querySelector('article');
const 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);
  const myRequest = new Request(pageId + '.txt');
  fetch(myRequest).then(function(response) {
    return response.text().then(function(text) {
      myArticle.innerHTML = text;
    });
  });
}

规范

规范 状态 备注
Fetch
text()
Living Standard

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
text
Experimental
Chrome Full support 42
Full support 42
Full support 41
Disabled
Disabled From version 41: this feature is behind the Experimental Web Platform Features preference. To change preferences in Chrome, visit chrome://flags.
Edge Full support ≤18Firefox Full support 39
Full support 39
Full support 34
Disabled
Disabled From version 34: this feature is behind the dom.fetch.enabled preference. To change preferences in Firefox, visit about:config.
IE No support NoOpera Full support 29
Full support 29
Full support 28
Disabled
Disabled From version 28: this feature is behind the Experimental Web Platform Features preference.
Safari Full support 10WebView Android No support NoChrome Android Full support 42Firefox Android No support NoOpera Android Full support 29
Full support 29
Full support 28
Disabled
Disabled From version 28: this feature is behind the Experimental Web Platform Features preference.
Safari iOS Full support 10Samsung Internet Android No support No

Legend

Full support  
Full support
No support  
No support
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
User must explicitly enable this feature.
User must explicitly enable this feature.

See also