我们目前有一个 python 脚本,它使用 Twitter API 生成包含用户最新推文的文本文件。
我们现在需要以某种方式在网页中显示它们,因此我们尝试使用 XMLHttpRequest 读取本地文本文件并显示它。目前格式并不重要,我们只是尝试直接从文件中读取。
到目前为止,我们的代码主要来 self 们在网上找到的代码,如下:
<!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
。
关于javascript - 使用 HTML 和 Javascript 读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31720770/