无需刷新整个页面即可自动刷新在线用户表

时间:2015-06-09 05:30:08

标签: javascript php jquery html

我有一个表格,显示我的信息中心页面中的在线和离线用户列表。我尝试每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>

我在不同的线程上发现了这个代码,但是当我尝试在我的项目中使用它时,它并没有在我的表中加载数据。我不太熟悉使用javascripts或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>

2 个答案:

答案 0 :(得分:3)

在你的情况下完全为你工作。

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

然后ajax会每隔3秒给你一次结果。

我希望它对你有用。

答案 1 :(得分:1)

确保你加载了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);