自动刷新在线用户表而不刷新整个页面

Auto refresh of online users table without refreshing whole page

本文关键字:刷新 在线 用户      更新时间:2023-09-26

我有一个表,显示仪表板页面中的在线和离线用户列表。我试图每隔5秒自动刷新整个表,以显示是否有其他用户刚刚登录或退出而不刷新整个页面。我已经搜索了不同的线程和页面,这告诉我应该使用AJAX或JSP。但我似乎做不到。

这是我的表:

<div class="col-md-2">
  <table class="table table-striped">
    <thead>
      <tr>
        <th>Status</th>
        <th>&nbsp;</th>
      </tr>
    </thead>
    <tbody>
      <?php
        $online = DB::table('users')->where('group_id', $user->group_id)->orderBy('online', 'desc')->get();
        foreach($online as $val=>$key)
        { ?>
          <tr>
            <td><?php if ($key->online == 1) { echo '<span class="label label-success">Online</span>'; } else { echo '<span class="label label-warning">Offline</span>'; } ?></td>
            <td><?=$key->first_name." ".$key->last_name?></td>
          </tr>
      <?php } ?>
    </tbody>
</table>

我在一个不同的线程上发现了这个代码,但是当我试图在我的项目上使用它时,它没有在我的表中加载数据。我不是很熟悉javascript或AJAX的工作,所以我希望你能帮助我。我将不胜感激。

<script>
    $(document).ready(function(){
        $("#refresh").click(function() 
        {
            $("#Container").load("content-that-needs-to-refresh.php");
            return false;
        });
    });
</script>
<div id="Container">
<?php include('content-that-needs-to-refresh.php'); ?>
</div>
<a href="#" id="refresh">Refresh</a>

在你的情况下完美地为你工作。

setInterval(function()
{
   //call ajax here..for your table result
}
}, 3000);    

,然后ajax会给你的结果每3秒。

我希望它对你有用。

确保加载了jQuery。你可以使用Google CDN或保存它并加载到你自己的服务器上。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
使用setInterval

<script>
    $(document).ready(function(){
        var refreshUsers = setInterval(function() {
            $("#Container").load("content-that-needs-to-refresh.php");
        }, 5000); // 5000 ms = 5 sec
    });
</script>
<div id="Container">
<?php include('content-that-needs-to-refresh.php'); ?>
</div>

如果你想停止刷新,使用

clearInterval(refreshUsers);