简体   繁体   中英

Unable to display the contents of a text file in an html webpage

I'm learning how to use html and javascript, and I've been trying to create a html webpage that gets the contents of a text file, info.txt, and displays it on the webpage as soon as the webpage is opened.

My problem is that the contents of the text file will not show up on the webpage. I've tried opening my html file on Chrome and FireFox, but the info.txt's contents won't show up. I'm storing the text and html files in the same folder.

I've attached my html code and info.txt. If anyone could give me some pointers on how to resolve this, I'd really appreciate it!

<!DOCTYPE html>
<html>
<body>

<h2>Info</h2>

<script type = 'text/javascript'>

function read_file() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      var e = document.getElementById('info');
      e.innerHTML = xhttp.responseText;
    }
  };
  xhttp.open('GET', 'info.txt', true);
  xhttp.send();
}
read_file();

</script>

</body>

</html>

info.txt:

Dan, Green Tea
Lola, Earl Grey
De, Matcha
Pearl, Coffee

You don't have any html element with an id="info".

var e = document.getElementById('info');

This is trying to find that element with the id, but there isn't one.

I think what you need to do is create some sort of element, maybe a paragraph element that has this id. <p id="info"></p>

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