简体   繁体   中英

javascript automatically read the file in the same directory, and put it on the content

is it possible on HTML page load, automatically (without the user input)read the file in the same directory, and put it on the content?

consider text file (a.txt) in the same folder as my HTML file (index.html)

for example

var reader = new FileReader();
    reader.onload = function (e) {
    const fileText = await fetch("a.txt").text();
    const tagElement = document.getElementById("about_layer");
    tagElement.innerText = fileText; 
    }

``

Fetch returns a Promise that resolves to a Response object. If you want to decode the response as text, then you'll have to await the text() method as it also returns a Promise , which resolves to a string.

As for on page load , just make sure you add a defer tag to your script to ensure that your script is called after the DOM is loaded.

(async function() {
  try {
    const response = await fetch("a.txt");
    const fileText = await response.text();
    const tagElement = document.getElementById("about_layer");
    tagElement.innerText = fileText; 
  } catch (error) {
    console.log(error);
  }
}())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM