如何使HTML页面将TXT文件解释为HTML代码?

huangapple go评论102阅读模式
英文:

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();
});

请注意,evalnew 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.

huangapple
  • 本文由 发表于 2023年3月10日 01:09:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75687863.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定