[英]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.