【问题标题】:Refresh page when file on server change [closed]服务器上的文件更改时刷新页面[关闭]
【发布时间】:2021-06-15 22:14:49
【问题描述】:

在我的 wwwroot 中,我放置了文件 123.txt。我的简单服务将字符串放入此文件。此外,在 index.php 中,我使用 123.txt 的内容作为变量。 123.txt文件更改时如何强制浏览器刷新页面?

【问题讨论】:

    标签: php apache refresh


    【解决方案1】:

    您可以在页面加载时在 javascript 中设置该值,然后每 X 秒轮询一次文件以查看它是否已更改。

    <script type="text/javascript">
    let originalValue = "<?php echo file_get_contents('123.txt'); ?>";
    function checkFileForChanges() {
        var xmlhttp = new XMLHttpRequest();
    
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
               if (xmlhttp.status == 200) {
                   if (xmlhttp.responseText != originalValue) {
                       window.location.reload();
                   }
               }
               else if (xmlhttp.status == 400) {
                  //alert('There was an error 400');
               }
               else {
                  // alert('something else other than 200 was returned');
               }
            }
        };
    
        xmlhttp.open("GET", "123.txt", true);
        xmlhttp.send();
    }
    
    let interval = setInterval(()=> {
    checkFileForChanges();
    }, (30*1000)) // every 30 seconds
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-31
      • 2016-07-25
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多