使用HTML和Javascript

时间:2015-07-30 10:03:27

标签: javascript html xmlhttprequest text-files

我们目前有一个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>

提前致谢。

编辑:

我们遇到的问题是它不输出任何内容,无论文本文件中写了什么。它会打印出&#34;测试。 &#34;我们用来确保函数被调用的字符串。

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

1 个答案:

答案 0 :(得分:1)

如果您在处于关闭状态的文档上调用document.write(文档将在DOM中进行完全解析),它将隐式调用消除的document.open现有文件

然后你写出 Test。,你可以看到。

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

请勿使用document.write