【问题标题】:Auto refreshing php page自动刷新php页面
【发布时间】:2015-04-12 11:49:39
【问题描述】:

我为我的网站制作了这个简单的聊天网站,但我不知道如何让它在每次发送消息时自动刷新。

发送和打印所有消息的网站:

<form action="messages.php" method="POST">
    <input name="chat_box" /><br>
    <input type="submit" value="Send" />
</form>


<?php
include "messages.txt";
?>

将文本输入发送到文本文件的站点:

<?php

$messages = $_POST["chat_box"];

$handler=fopen("messages.txt", 'a');
fwrite($handler,$_SERVER["REMOTE_ADDR"].":".$messages."<br>");
fclose($handler);

header("Location: chat_box.php");

?>

谁能帮帮我?

【问题讨论】:

  • 您可能不想刷新页面,而只是更新页面上的“聊天记录”。有很多方法可以做到这一点,从 Web 套接字到简单地定期轮询 AJAX 资源。对于这个确切的应用程序,还有 无数 教程。也许在 Google 上快速搜索“简单的 php 聊天应用程序”会有所帮助?
  • 谢谢,会查一下

标签: php chat


【解决方案1】:

试试这个代码:

这是messages.php

<?php
    $page = $_SERVER['PHP_SELF'];
    $sec = "10";
?>
<html>
    <head>
    <meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
    </head>
    <body>
    <form action="messages.php" method="POST">
        <input name="chat_box" /><br>
        <input type="submit" value="Send" />
    </form>
    <?php
        include "messages.txt"; //Uncomment this to check the autorefresh
        echo "Auto refresh in 10 second!";

        $messages = $_POST["chat_box"];

        $handler=fopen("messages.txt", 'a');
        fwrite($handler,$_SERVER["REMOTE_ADDR"].":".$messages."<br>");
        fclose($handler);
    ?>
    </body>
</html>

希望对您有所帮助... :)

【讨论】:

    【解决方案2】:

    如果您打算接收新消息,最好的办法可能是每 10 秒重新加载一次文本文件。为此,将第一个代码集底部的 php 替换为:

    <div id="messages"></div>
    <script type="text/javascript"> 
       $(document).ready(function() {
         function functionToLoadFile(){
          jQuery.get('messages.txt', function(data) {
            $("#messages").html(data) 
          });
         }
    setInterval(functionToLoadFile, 10000);
    });
    </script>
    

    【讨论】:

    • 它不工作。可能是因为我没有安装 jquery。我可以使用 src="" 但我会保持这样并手动刷新它
    猜你喜欢
    • 2011-12-29
    • 2016-03-26
    • 2012-07-21
    • 2011-04-27
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    相关资源
    最近更新 更多