HTML - 如何将 .txt 文件的内容插入变量以使用 .innerHTML 更改 <body> 的内容?

问题描述

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

解决方法

您可以使用 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>

,

您可以为文本文件创建一个 AJAX call 并获取来自该调用的响应并将其设置为 .textContentdiv。这是一个示例(请参阅内联评论):

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
<div id="output"></div>