英文:
How do I make an HTML page interpret a TXT file as HTML code?
问题
我找到的只是如何显示TXT文件的数据,但我想要能够将该TXT文件解释并用作HTML代码来显示。
英文:
All I've found is how to display the data of the TXT file, but I want to be able to use that TXT file to be interpreted and used as HTML code to be displayed instead.
答案1
得分: 2
如果您指的是JavaScript,您唯一的选择就是执行类似于以下的操作:
fetch('/file.txt').then(e => e.text()).then(txt => {
let txtFunc = new Function(txt);
txtFunc();
});
请注意,eval
或new Function
不安全,大多数情况下不应使用。
英文:
If you mean JavaScript, your only option would be to do something like this:
fetch('/file.txt').then(e=>e.text()).then(txt=>{
let txtFunc = new Function(txt)
txtFunc()
})
Note that eval
or new Function
is not safe and should not be used in most cases.
答案2
得分: 0
将文件后缀更改为.html
而不是.txt
。
英文:
Change the file suffix to .html
instead of .txt
答案3
得分: 0
我使用了derder56的代码的一个略微修改版本来创建这个示例,该代码从文本文件中获取HTML代码并将其输出到result
div中。当然,你可以对文本文件的结果进行任何操作,例如在控制台中输出它。
<body>
<div id="result"></div>
</body>
<script>
fetch('file.txt').then(e => e.text()).then(txt => {
document.getElementById("result").innerHTML = txt;
})
</script>
请注意,由于CORS安全警告,由于CORS请求需要HTTP或HTTPS,你无法使用本地文件执行此操作。
英文:
I used a very slightly modified version of derder56's code for this example that takes HTML code from a text file and outputs it in the result
div. Of course, you could do anything with the result from the text file, such as outputting it in the console.
<body>
<div id="result"></div>
</body>
<script>
fetch('file.txt').then(e => e.text()).then(txt => {
document.getElementById("result").innerHTML = txt;
})
</script>
Keep in mind that due to a CORS security advisory, you wouldn't be able to do this with local files due to CORS requests requiring HTTP or HTTPS.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论