2015-06-09 24 views
7

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

如果你想每5秒钟后自动重新加载,然后使用'setTimeout'。但是我不明白'#refresh'的概念,当你想自动的时候点击这里!我假设你的'content-that-needs-to-refresh.php'包含你想要加载的'table'吗? –

+0

所以你发布的代码加载你的表一次,你问如何更新它,或者它从来没有工作?只是为了验证(正如你所提到的,你不熟悉JS)是否在页面上加载了jquery库? –

回答

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); 
+0

@YllanLacorte有没有反馈意见? –

3

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

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

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

我希望它能为你工作。