【问题标题】:Auto refresh of online users table without refreshing whole page自动刷新在线用户表而不刷新整个页面
【发布时间】:2015-06-09 05:30:07
【问题描述】:

我的仪表板页面中有一个表格显示在线和离线用户的列表。我试图每 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>

【问题讨论】:

  • 如果您想在每 5 秒后自动重新加载,请使用 setTimeout。但是我不明白#refresh的概念当你想要的时候自动点击这里!我假设您的content-that-needs-to-refresh.php 包含您要加载的table 对吗?
  • 那么您发布的代码是否加载了您的表格一次,您是在询问如何更新它,还是它从来没有工作?只是为了验证(正如您提到的您不熟悉 JS)您是否在页面上加载了 jquery 库?

标签: javascript php jquery html


【解决方案1】:

在你的情况下完全适合你。

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

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

我希望它对你有用。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • @YllanLacorte 有什么反馈吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 2014-01-10
    • 2016-11-28
    • 2014-03-23
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    相关资源
    最近更新 更多