javascript - 使用 `fetch()`在网页中显示纯文本

标签 javascript html fetch-api

<分区>

使用 Javascript 在 HTML 页面中显示字符串变量很容易:

<html>
<body>

<script>
text = "hello"
document.getElementById("demo").innerHTML = text
</script>

<p id="demo"></p>

</body>
</html>

但是我想用本地文件的内容替换“hello”,比如 file.txt。我认为这应该可以使用 Javascript 的 fetch() API 轻松完成,但我遇到了问题。这,

<html>
<body>

<p id="demo"></p>

<script>
text = fetch('file.txt').then(response => response.text())
document.getElementById("demo").innerHTML = text
</script> 

</body>
</html>

将显示[object Promise]。我想我必须以某种方式访问​​ response 对象,但我不知道这是如何完成的。

最佳答案

text 在您的代码中是一个 promise ,而不是文本。您需要使用 promise 回调:

fetch('file.txt')
.then(response => {
    if (!response.ok) {
        throw new Error("HTTP error " + response.status);
    }
    return response.text();
})
.then(text => {
    document.getElementById("demo").innerHTML = text;
})
.catch(error => {
    // Handle/report error
});

关于javascript - 使用 `fetch()`在网页中显示纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57411402/

相关文章:

javascript - 如果参数为空,则不附加到字符串

javascript - WCF 上的 CORS - 当请求来自客户端计算机时,为什么要指定 Web 服务器?

javascript - addEventListener() 方法 id 在 IE 11.0.12 中不起作用,似乎在 11.0.10 中起作用

javascript - fetch() 和 window.fetch() 有什么区别?

javascript - 即使在使用 'then' 之后,Fetch 也会返回 promise 而不是实际数据

javascript - 更改从事件监听器获取 URL?

javascript - FlatList 中的替代颜色

javascript - 我怎样才能让我的功能按计划运行?我的逻辑有错吗? (长的)

html - 将鼠标悬停在图像上时显示文本

html - 定位在图像上方和图像下方