Response:text() 方法
>备注: 此特性在 Web Worker 中可用。
Response 接口的 text() 方法将 Response 流读取至结束。它返回一个会兑现 String 的 promise。响应始终使用 UTF-8 解码。
语法
js
text()
参数
无。
返回值
一个会兑现 String 的 promise。
异常
AbortErrorDOMException-
请求已被中止。
TypeError-
由于以下原因之一而抛出:
- 响应主体已被扰乱或锁定。
- 解码主体内容时出错(例如,因为
Content-Encoding标头不正确)。
示例
在我们的 fetch 文本示例(在线运行 fetch 文本)中,我们有一个 <article> 元素和三个链接(存储在 myLinks 数组中)。首先,我们遍历所有这些链接,并为每一个设置 onclick 事件处理器,这样在点击某个链接时会运行 getData() 函数——并将该链接的 data-page 标识符作为参数传入。
当运行 getData() 时,我们使用 Request() 构造函数创建新请求,然后用它来获取特定的 .txt 文件。获取成功后,我们使用 text() 从响应中读取字符串,再把 <article> 元素的 innerText 设为该文本对象。
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 错误,状态 = ${response.status}`);
}
return response.text();
})
.then((text) => {
myArticle.innerText = text;
})
.catch((error) => {
myArticle.innerText = `错误:${error.message}`;
});
}
规范
| 规范 |
|---|
| Fetch> # ref-for-dom-body-text①> |