【问题标题】:Update Chat Every second php更新聊天每秒 php
【发布时间】:2016-03-27 16:21:14
【问题描述】:

你好,我有我的脚本,但这不起作用我不能每秒更新聊天你能帮我从数据库每秒更新聊天吗(请不要更新 div 仅文本)

index.php

<html>
    <head>
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script>
        $(document).ready(function(){

        setTimeout(
        function() {updateChat();},
        1000);

        function updateChat() {
        $.get("read.php", function(data)
        {
          $("#Show_Data").html(data);
        });
        }
        });
        </script>
    </head>
    <body>
        <div id="Show_Data"></div>
    </body>
</html>

读取.php

<?php
include("config.php");

$Data = "SELECT * FROM chat ORDER BY Time ASC";
$Result = mysqli_query($Connection, $Data);

while($row = mysqli_fetch_array($Result,MYSQLI_ASSOC))
{
    echo '</br>' .$row['name'];
}

mysqli_free_result($Result);
mysqli_close($Connection);
?>

这是我的代码,但是当我在数据库中插入数据时,我的代码不会更新 html 中的数据

【问题讨论】:

  • 现在你有什么结果?
  • 您的 get 请求是否返回了您需要的数据?请您澄清一下您正在努力解决的问题的哪一部分?
  • 不要这样做。你会用很少的用户杀死你的服务器。改用 websockets
  • @rjdown 怎么用?
  • 最好用谷歌搜索教程,虽然很简单,但不用担心!

标签: php chat


【解决方案1】:

选项 1:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script>
        $(document).ready(function(){


        setTimeout(
        function() {updateChat();},
        1000);

        function updateChat() 
        {
         $.get("read.php")
         .done(function(data)
         {
           //You can do futher checks here....
           $("#Show_Data").html(data);
           setTimeout(function() {updateChat();},1000);
         })
         .fail(function()
         {
            //error 404 or 500
         });
        }
      });
        </script>
    </head>
    <body>
        <div id="Show_Data"></div>
    </body>
</html>

在上面的代码中,当调用出现问题时,它会停止并且不会继续执行。

选项2:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script>
        $(document).ready(function(){

        setInterval(
        function() {updateChat();},
        1000);

        function updateChat() {
        $.get("read.php", function(data)
        {
          $("#Show_Data").html(data);
        });
        }
        });
        </script>
    </head>
    <body>
        <div id="Show_Data"></div>
    </body>
</html>

ajax 调用每 1000 毫秒执行一次代码,无论调用是否成功

【讨论】:

  • 这是正确的,但 div 有问题,请参阅检查元素
  • 我无法理解您的评论。
【解决方案2】:

您需要使用 setInterval 而不是 setTimeout(它只运行一次)。

如果这没有帮助,请发布您遇到的任何 PHP/JavaScript 错误。
为确保将 PHP 错误设置为显示,请将 error_reporting(E_ALL) 添加到脚本顶部。

要查看 JavaScript 错误,请在浏览器中打开开发者工具 (F12) 并转到控制台

【讨论】:

    猜你喜欢
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多