簡體   English   中英

HTML-如何將 .txt 文件的內容插入到變量中以使用 .innerHTML 更改其內容?

[英]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文件並將其上傳到服務器來更改<body>內的<div>的內容。 我仍然是大學的早期學生,我還沒有學習 PHP 和 JQuery。 所以我試圖通過僅使用 Javascript 和 HTML 來實現這一點。 我只需要一種方法,將我在 .txt 文件中寫入的任何內容再次寫入 <div class="CONTENT" id="target"> 中,該<div class="CONTENT" id="target"> > 自動位於<body>中。 非常感謝任何想法和建議!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM