简体   繁体   English

无法在 html 网页中显示文本文件的内容

[英]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.我正在学习如何使用 html 和 javascript,并且我一直在尝试创建一个 html 网页,该网页获取文本文件 info.txt 的内容,并在网页打开后立即将其显示在网页上。

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.我试过在 Chrome 和 FireFox 上打开我的 html 文件,但是 info.txt 的内容不会显示。 I'm storing the text and html files in the same folder.我将文本和 html 文件存储在同一个文件夹中。

I've attached my html code and info.txt.我附上了我的 html 代码和 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:信息.txt:

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

You don't have any html element with an id="info".您没有任何带有 id="info" 的 html 元素。

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

This is trying to find that element with the id, but there isn't one.这是试图找到具有 id 的元素,但没有。

I think what you need to do is create some sort of element, maybe a paragraph element that has this id.我认为您需要做的是创建某种元素,可能是具有此 ID 的段落元素。 <p id="info"></p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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