繁体   English   中英

javascript fetch 命令不显示 html 页面上的内容

[英]javascript fetch command does not display the content on the html page

我在 HTML 文件的同一目录中有一个简单的文本文件,我使用 javascript 中的 fetch 命令在页面加载完成时在页面 div 部分显示文本文件内容

但是,我的代码不起作用并且没有显示任何内容,我的问题是 fetch 命令是否适合这样的任务,或者我应该使用文件阅读器吗?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Page</title>
<meta name="generator" >
<style type="text/css">
</style>
<script type="text/javascript"  defer>     
 const myfile=location.href.slice(0,location.href.lastIndexOf("/"))+"/a.txt"

console.log(myfile);

async function getTextFile1() {
  try {
  
    const response = await fetch(myfile, { mode: 'no-cors' }); 
    const fileText = await response.text();
    //console.log(window.location);
    //console.log(window.location.href);
    
    const tagElement = document.getElementById("about_layer");
    tagElement.innerText = fileText; 
  } catch (error) {
    console.log(error);
  }
 }
 

window.onload = getTextFile1;
</script> 
</head>
<body>
<div  >should be placed here    </div>
   <div id="about_layer">
   </div>
</body>
</html>

您的代码没有任何问题,只需尝试使用开发服务器运行html文件即可。

您可以为此使用Live Server Visual Studio 代码扩展。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM