【问题标题】:How to get file contents of a file automatically with AJAX?如何使用 AJAX 自动获取文件的文件内容?
【发布时间】:2015-07-05 00:12:18
【问题描述】:

当我按下按钮时,我正在使用 AJAX 获取文件的内容(我对 AJAX 很陌生。),这是 HTML:

<!DOCTYPE html>
<html>

<head>
  <script>
    function loadXMLDoc() {
      var xmlhttp;

      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() {

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

          document.getElementById("myDiv").innerHTML = xmlhttp.responseText;

        }
      }

      xmlhttp.open("GET", "data.dat", true);
      xmlhttp.send();

    }
  </script>
</head>

<body>

  <div id="myDiv">
    <p>- - -</p>
  </div>
  <button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>

</html>

这是用于更改文件的python(这不是我正在使用的python代码,但它仍然做同样的事情,几乎):

from time import *
a = 0

while True:
    print(a)
    file = open("data.dat","w")
    file.write("<p>"+str(a)+"</p>")

    file.close()
    sleep(1)
    a+=1

我想每秒获取文件内容,我该怎么做?任何帮助都是好的。

【问题讨论】:

    标签: python html ajax file


    【解决方案1】:

    您可以使用setInterval() 定期运行更新文档的功能。

    var intervalID = setInterval(loadXMLDoc, 1000); // Every 1s
    

    【讨论】:

    • 这有点工作,它确实更新了页面,但它用相同的值更新了它。我该如何解决?
    • 没关系,这不是代码。这是我的 Web 服务器,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    相关资源
    最近更新 更多