Javascript SetInterval($。获取30秒的池

Javascript SetInterval($。获取30秒的池,javascript,php,pool,Javascript,Php,Pool,为了避免在我的服务器上执行多个请求,我尝试实现一个池:因此,我每30秒执行一次请求,如果它找到数据,或者如果30秒过去了,就向我发送一次数据 //getchat.php $pool=0; $chatmsg= array(); while($pool<30 && count($chatmsg)==0){ $result = mysqli_query($con,"SELECT * FROM chat WHERE id > ".addslashes($_GET

为了避免在我的服务器上执行多个请求,我尝试实现一个池:因此,我每30秒执行一次请求,如果它找到数据,或者如果30秒过去了,就向我发送一次数据

//getchat.php

$pool=0;
$chatmsg= array();

while($pool<30 && count($chatmsg)==0){

    $result = mysqli_query($con,"SELECT * FROM chat WHERE id > ".addslashes($_GET['id'])." ORDER BY id ASC");
    $i=0;
    while($row = mysqli_fetch_assoc($result)) {
        $chatmsg[$i]=array("message"=>htmlspecialchars_decode(htmlentities($row["message"])));
        $i++;
    }

    sleep(1);
    $pool++;
}

echo json_encode($chatmsg);
flush();
但是信息在30秒后显示!我做错了什么

编辑:我终于发现:

函数getchat(){
$.get(“getchat.php”{
id:chatid
},函数(数据){
控制台日志(数据);
getchat();
});

}
消息在30秒后显示,因为您有一个时间间隔。只有在30秒后才会调用它。如果您想立即调用它,您可以按如下方式更改代码:

//script.js

function getChat() {
    $.get("getchat.php", {
        id: chatid
    }, function(data) {
        console.log(data);
    });
}
getChat();
setInterval(getChat, 30000);
编辑

我做了自己的测试来重现这种情况:

// index.php
while (!file_exists(__DIR__ . '/flag')) {
    sleep(1);
}

echo date('r');
flush();
die;


// index.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript"> 

function getChat() {
     $.get(
         "index.php", 
         {}, 
         function(data) {
             console.log(data);
         }
     );
}
getChat();
setInterval(getChat, 10000);
</script>
</head>
<body>
</body>
</html>
//index.php
当(!file_存在时(_DIR__.'/flag')){
睡眠(1);
}
回音日期('r');
冲洗();
死亡
//index.html
函数getChat(){
美元(
“index.php”,
{}, 
功能(数据){
控制台日志(数据);
}
);
}
getChat();
设置间隔(getChat,10000);
无论何时调用index.html,我都可以在控制台中看到一个挂起的请求。创建文件“flag”后,它会立即停止,并在console.log中获得一个日期

我可以建议你做两件事:

  • 重新检查控制台是否有挂起的请求。它们应该正在那里运行

  • 在php代码中重新创建更简单的情况,而不涉及DB


  • 如果你从浏览器中调用“GigChald.php?id?AdID”,会发生什么?它真的会返回任何JSON吗?是的,它确实是!我有所有的JSONE,你应该考虑Web套接字,而不是使用<代码>睡眠()。就像您的服务器端代码中那样。是的,我已经有了这个,但是当我发送一条新消息后,它不会立即显示。为什么它会立即显示?您只需要每30秒调用一次更新。如果您在php端睡眠,您也可以将setInterval time更改为1秒。但这会在某个时候中断您的服务器,因为它是ould显示挂起的最后一个setInterval请求的请求
    // index.php
    while (!file_exists(__DIR__ . '/flag')) {
        sleep(1);
    }
    
    echo date('r');
    flush();
    die;
    
    
    // index.html
    
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script type="text/javascript"> 
    
    function getChat() {
         $.get(
             "index.php", 
             {}, 
             function(data) {
                 console.log(data);
             }
         );
    }
    getChat();
    setInterval(getChat, 10000);
    </script>
    </head>
    <body>
    </body>
    </html>