Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用“fetch()”在网页中显示纯文本_Javascript_Html_Fetch Api - Fatal编程技术网

Javascript 使用“fetch()”在网页中显示纯文本

Javascript 使用“fetch()”在网页中显示纯文本,javascript,html,fetch-api,Javascript,Html,Fetch Api,使用Javascript在HTML页面中显示字符串变量很容易: <html> <body> <script> text = "hello" document.getElementById("demo").innerHTML = text </script> <p id="demo"></p> </body> </html> 将显示[对象承诺]。我想我必须以某种方式访问响应对象,但我不知道这是如

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

<html>
<body>

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

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

</body>
</html>

将显示
[对象承诺]
。我想我必须以某种方式访问
响应
对象,但我不知道这是如何实现的。

代码中的
文本
是一种承诺,而不是文本。您需要使用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
});

text
在代码中是承诺,而不是文本。您需要使用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
});

问题是,在问题解决并获得文本之前,您正在执行
document.getElementById(“demo”).innerHTML=text
。试着做

text = fetch('file.txt').then(response => {
   document.getElementById("demo").innerHTML = response.text()
})

问题是,在问题解决并获得文本之前,您正在执行
document.getElementById(“demo”).innerHTML=text
。试着做

text = fetch('file.txt').then(response => {
   document.getElementById("demo").innerHTML = response.text()
})
response.text()
还返回一个承诺。因此,你必须添加另一个,然后才能得到文本

response.text().then(function (text) {
  // do something with the text response 
});
response.text()
还返回一个承诺。因此,你必须添加另一个,然后才能得到文本

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

您需要等待
fetch
完成。试着像这样使用
wait
text=wait-fetch('file.txt')。然后(response=>response.text())document.getElementById(“demo”).innerHTML=text
@Nimad这似乎不起作用。您需要等到
fetch
完成。试着像这样使用
Wait
text=Wait fetch('file.txt')。然后(response=>response.text())document.getElementById(“demo”).innerHTML=text
@Nimad这似乎不起作用。等等。这件事一定有个替身。对,标记CW和off以查看…等等。这件事一定有个替身。对,标记CW和off以查看…这将产生与我的原始(非工作)代码相同的输出。这将产生与我的原始(非工作)代码相同的输出。