重新加载聊天内容,无需按F5



我想与PHP创建一些聊天。一切正常,但是聊天不会自动重新加载。有能力解决我的问题吗?

我的PHP代码:

<?php
  $newmsg= mysqli_query($db_chat, "SELECT msg, username, time FROM messages");
  while($row = mysqli_fetch_object($newmsg))
  {
      echo '<div class="messagesinchat">';
        if ($row->username == "admin") {
          echo '<div class="ownmsg">';
          echo $row->username. ":&nbsp " . $row->msg;
          echo "<br />";
          echo '</div>';
        }
        else{
          echo $row->username. ":&nbsp" . $row->msg;
          echo "<br />";
        }
      echo '</div>';
  }
    ?>

您需要在显示页面中定义您的div,并且可以使用JQuery的.load()使用PHP脚本将聊天消息加载到div中。然后,每x秒,重新加载您的div

假设您有:
display.php实际上,很好。显示您的聊天。(<div id='messagesinchat>应该在这里。

display.php中,有类似的jQuery:

$(function() {
    setInterval(function() {
        $('#messagesinchat').load('chat.php?action=show');
    }, 1000);
});

chat.php?action=show中,您执行查询以搜索和打印您的消息。

您可以根据需要在几秒钟后重新加载页面。

<script>
 setTimeout(function(){
  window.location.reload(1);
 }, 5000);
</script>

<meta http-equiv="refresh" content="5; URL=http://yoursite.com/chat.php">

您可以使用php:

进行操作

header("Refresh:0");

请参阅彼得·莫滕森(Peter Mortensen)在此处的堆栈溢出的答案

最新更新