javascript获取命令不会在html页面上显示内容



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

然而,我的代码不起作用,也没有显示任何内容,我的问题是fetch命令适合这样的任务吗?还是应该使用filereader?

<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 Servervisualstudio代码扩展来实现这一点。

最新更新