使用 HTML 和 Javascript 从文本文件中读取

Reading from text file with HTML and Javascript

我们目前有一个 python 脚本,它使用 Twitter API 生成包含用户最新推文的文本文件。

我们现在需要以某种方式在网页中显示它们,因此我们尝试使用 XMLHttpRequest 来读取本地文本文件并显示它。目前格式化并不重要,我们只是尝试直接从文件中读取。

目前我们的代码主要来自网上找到的代码如下:

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
    document.write("Test. ");
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
  }
xmlhttp.open("GET","twitterFeed.txt",false);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

提前致谢。

编辑:

我们遇到的问题是它不输出任何内容,无论文本文件中写入了什么。它确实打印出我们用来确保函数被调用的 "Test. " 字符串。

据我们所知,没有出现任何 js 或网络错误。

如果您在关闭状态的文档上调用 document.write(文档将处于关闭状态,因为 DOM 将被完全解析),它将隐式调用 document.open清除现有文档

然后你写出测试。,你可以看到。

将要删除的内容中有 <div id="myDiv"></div>,因此 document.getElementById("myDiv").innerHTML=xmlhttp.responseText; 将失败。

不要使用document.write