【问题标题】:HTML- How can I insert the contents of a .txt file into a variable to use .innerHTML to change the contents of <body>?HTML - 如何将 .txt 文件的内容插入到变量中以使用 .innerHTML 更改 <body> 的内容?
【发布时间】:2023-04-02 06:10:02
【问题描述】:

我正在尝试创建一个用于 HTML 页面处理的自动化系统,我将能够在其中更改内容 &lt;body&gt; 内部的&lt;div&gt; 通过写入外部.txt 文件并将其上传到服务器。我仍然是大学的早期学生 而且我还没有学习 PHP 和 JQuery。所以我试图通过只使用 Javascript 和 HTML 来实现这一点。 我只需要一种方法,将我在 .txt 文件中写入的任何内容再次写入 &lt;div class="CONTENT" id="target"&gt; 中,&lt;body&gt; 自动位于 &lt;body&gt; 中。非常感谢任何想法和建议!

【问题讨论】:

  • 您可能希望在服务器中处理此问题。也许不是重写 HTML 文件,而是让服务器抓取所有 .txt 文件,将它们包装在
    标签中,然后将整个内容包装在 HTML 标签中,最后将该 HTML 作为响应发送给客户端。跨度>

标签: javascript html external txt


【解决方案1】:

您可以为文本文件创建一个AJAX call,并从该调用中获取响应并将其设置为div.textContent。这是一个示例(参见 cmets inline):

const output = document.getElementById("output");

// Create XHR object
var xhr = new XMLHttpRequest();

// Configure the request (substitute a URL
// to the file below)
xhr.open("GET", filePathHere, false);

// Set up the callback for when the response has
// been recieved
xhr.onreadystatechange = function (){
 if(xhr.readyState === 4) {
   // Was the request successful?
   if(xhr.status === 200 || xhr.status == 0) {
     // Populate the <div> with the response text
     output.textContent = xhr.responseText;
   }
 }
}
xhr.send(null);  // Make the call
&lt;div id="output"&gt;&lt;/div&gt;

【讨论】:

    【解决方案2】:

    您可以使用 FileReader 解决您的问题。 看看 this answer.

    function readSingleFile(e) {
        var file = e.target.files[0];
        if (!file) {
            return;
        }
        var reader = new FileReader();
        reader.onload = function (e) {
            var contents = e.target.result;
            displayContents(contents);
        };
        reader.readAsText(file);
    }
    
    function displayContents(contents) {
        var element = document.getElementById('target');
        element.textContent = contents;
    }
    
    document.getElementById('file-input')
        .addEventListener('change', readSingleFile, false);
    <html>
    
    <head></head>
    
    <body>
        <input type="file" id="file-input" />
        <h3>Contents of the file:</h3>
        <div id="target" class="CONTENT"></div>
    </body>
    
    </html>

    【讨论】:

    • 只有链接的答案不应该是答案。应该是评论。
    • 您所做的只是从链接中复制代码。仍然是一个链接唯一的答案。您没有添加任何不在链接中的内容。
    • 感谢@ScottMarcus 的澄清。我不能评论少于 50 的声誉。我应该删除响应吗?
    • 是的,你真的应该这样做。现在,专注于提供高质量的答案来提升您的声誉。您可能想阅读How to answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 2012-12-07
    • 2020-09-17
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 2017-09-25
    相关资源
    最近更新 更多