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



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

您可以使用 FileReader 解决您的问题。 看看 这个答案。

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 调用,并从该调用中获取响应并将其设置为div.textContent。下面是一个示例(请参阅内联注释):

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>

最新更新