【问题标题】:Refresh content external .txt file in PHP page在 PHP 页面中刷新内容外部 .txt 文件
【发布时间】:2012-04-27 17:00:50
【问题描述】:

我已经看过类似的问题,但还没有完全找到我要找的东西......

我有一个用 PHP 编写的网页,我需要显示外部 .txt 文件的内容,并且我需要每隔 20 秒刷新一次,因为 .txt 文件内容会定期更改。

我已经能够通过放入一个 IFRAME 并使用 PHP 包含来显示文件的内容来实现这一点。然后我每 20 秒刷新一次包含页面。

这工作得很好,除了 IFRAME 刷新对我的网站统计数据造成严重破坏,因为刷新量,ehcih 计入网页浏览量。

我可以使用 AJAX 或其他方式来执行此操作吗?我确定它们可能是另一种在不严重影响我的统计数据且不会对服务器造成太大负载的情况下执行此操作的方法?

请提供尽可能多的具体说明,因为我已经花了几天的时间来实现我已经拥有的!

非常感谢!

【问题讨论】:

  • 不能直接把外部的.txt文件放到iframe中,让客户端直接从源服务器加载吗?如果没有,您将不得不调整它们收集统计信息的方式,以便 AJAX 请求不会count against pageviews
  • 您是在刷新页面还是 iframe?如果 iframe 的内容在同一个域中,则很容易重新加载它。

标签: php html ajax iframe


【解决方案1】:

您绝对可以在 PHP 中使用 Comet/Long Polling 之类的东西,但正如 the accepted answer to this question 所提到的,使用时有一些注意事项,例如Apache 作为服务器。

如果您不限于 PHP,您可以使用 socket.io,它非常适合该原因。此外,如果您的客户不多,Comet 仍然可以满足您的需求。

【讨论】:

    【解决方案2】:

    我会根据会话隐藏 Google Analytics JavaScript,以便它只为该会话加载一次:

    <?php
    session_start();
    if (!isset($_SESSION['beenHere']) || !$_SESSION['beenHere']) {
    ?>
      <!-- ga.js javascript here -->
    <?php
    } else {
      $_SESSION['beenHere'] = true;
    }
    ?>
    

    然后您可以根据需要继续重新加载页面。然而,这是假设您需要用 PHP 加载文本文件?否则,你可以不只是将文本文件加载到 iFrame 中,并使用 JavaScript setTimeout 调用来刷新 iframe src 吗?

    【讨论】:

      【解决方案3】:

      我知道您要求使用 Ajax/JavaScript,但 Java 小程序可与大多数桌面浏览器一起使用,而且此任务在 Java 中会非常简单,因此我为您提供了一个示例,说明如何使用 Java 小程序执行此操作。

      // PHP/HTML embed code
      <APPLET CODE="readTextFile.class" width=400 height=300>
          <PARAM NAME="fileToRead" VALUE="<?php echo $textfile ?>">
          Your browser does not support the <code>applet</code> tag.
      </APPLET>
      

      您需要在 cmd.exe 中编译 javac "path/to/readTextFile.java" 之类的 java 文件

      // readTextFile.java
      
      import java.applet.*;
      import java.awt.*;
      import java.io.*;
      import java.net.*;
      import java.util.*;
      
      public class readTextFile extends Applet {
      
         String fileToRead = "path/to/myfile.txt";
         StringBuffer strBuff;
         TextArea txtArea;
      
         public void init(){
             txtArea = new TextArea(300, 400);
             txtArea.setEditable(false);
             add(txtArea, "center");
      
             // First try the HTML applet parameter, if not use fileToRead variable
             String prHtml = this.getParameter("fileToRead");
             if (prHtml != null) fileToRead = new String(prHtml);
      
             // Set up a timer to read the file every 20 seconds
             Timer t = new Timer();
             t.scheduleAtFixedRate(new TimerTask() {
                 public void run() {
                     readFile();
                 }
             }, 0, 20*1000);
         }
      
        public void readFile(){
             String line;
             URL url = null;
             try{
                 url = new URL(getCodeBase(), fileToRead);
             } catch (MalformedURLException e) {
                 //handle or do nothing
             }
      
             try {
                 InputStream in = url.openStream();
                 BufferedReader bf = new BufferedReader(new InputStreamReader(in));
                 strBuff = new StringBuffer();
                 while((line = bf.readLine()) != null){
                     strBuff.append(line + "\n");
                 }
                 txtArea.append("File Name : " + fileToRead + "\n");
                 txtArea.append(strBuff.toString());
             } catch(IOException e) {
                 e.printStackTrace();
             }
         }
      }
      

      这将从您的服务器每 20 秒读取一次文件。只要确保您尝试访问的文件位于同一文件夹中或在您放置 readTextFile.class 的任何下方(但不在上方)中

      请注意,文本文件将获得同样多的疯狂点击(但没有办法解决),但您的页面不会获得疯狂点击。

      【讨论】:

        【解决方案4】:

        如果您使用的是 jquery,您可以尝试以下代码: 它将获取文本文件并将内容放在 id 为 textdiv 的 div 中

        <script type='text/javascript'>
        var doInterval;
        function getfile() {
          $.ajax({
            url: "file.txt",
            complete: function(request){
              $("#textdiv").html(request.responseText);
            }
          });
        }
        doInterval = setInterval(getfile, 20000);
        </script>
        <div id="textdiv"></div>
        

        【讨论】:

        • 您好,我如何使用 jquery 实现此代码?我目前没有jquery?谢谢
        • 你可以通过在 标签之间添加 jquery 库 &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"&gt;&lt;/script&gt;
        【解决方案5】:

        我会建议 Prototype ;它支持定期更新,开箱即用!在您的页面上获取并包含该原型 JS 脚本(从 here 下载)。然后将此脚本添加到脚本块中。

        new Ajax.PeriodicalUpdater('logger', 'path/to_file.php',
        { 
            method:'post',
            parameters: {sender:'mrigesh',reciever:'browser'},
            frequency: 20,
            decay: 2
        });
        

        因此,您的“路径/to_file.php”将提供需要定期更新的信息部分。根据您的喜好查看更改频率(我在您的问题中看到了 20 个!)。 Decay 是一项功能,如果一次又一次地接收到相同的数据,它可以延迟发送到服务器的请求周期... API 路径:read

        【讨论】:

          猜你喜欢
          • 2013-06-25
          • 1970-01-01
          • 2011-02-11
          • 1970-01-01
          • 2016-06-10
          • 2021-07-05
          • 2023-04-10
          • 2016-02-04
          • 1970-01-01
          相关资源
          最近更新 更多