[英]HTML- How can I insert the contents of a .txt file into a variable to use .innerHTML to change the contents of <body>?
Im trying to create an automated system for HTML page handling where I will be able to change the contents of a <div>
inside <body>
by writing into an external .txt
file and uploading it to the server.我正在尝试为 HTML 页面处理创建一个自动化系统,我将能够通过写入外部
.txt
文件并将其上传到服务器来更改<body>
内的<div>
的内容。 Im still an early student in university and I havent learned PHP and JQuery yet.我仍然是大学的早期学生,我还没有学习 PHP 和 JQuery。 So I am trying to accomplish this by using only Javascript and HTML.
所以我试图通过仅使用 Javascript 和 HTML 来实现这一点。 I just need a way for whatever I write inside the.txt file to be written again inside the
<div class="CONTENT" id="target">
which is inside the <body>
automatically.我只需要一种方法,将我在 .txt 文件中写入的任何内容再次写入 <div class="CONTENT" id="target"> 中,该
<div class="CONTENT" id="target">
> 自动位于<body>
中。 Any thoughts and suggestions are greatly appreciated!非常感谢任何想法和建议!
You can solve your problem by using the FileReader.您可以使用 FileReader 解决您的问题。 Have a look to 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>
You can make an AJAX call for the text file and take the response from that call and set that as the .textContent
of the div
.您可以对文本文件进行AJAX 调用,并从该调用中获取响应并将其设置为
div
的.textContent
。 Here's an example (see comments 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
<div id="output"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.