2015-06-09 27 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秒的結果。

我希望它能爲你工作。