数据库更新后刷新数据表


refresh datatable after database update

在我的html页面中,我有一个表,用于显示来自数据库的数据。我想在数据库更新时刷新数据表,而不刷新所有页面。我使用的是PHP框架Laravel。

<table id="example" class="table">
    <thead>
    <tr class="headings">
        <th>ID &nbsp;&nbsp;&nbsp;</th>
        <th>first name </th>
        <th>last name </th>
        <th>E-mail </th>
        <th>birthday </th>
    </tr>
    </thead>
    <tbody>
    @foreach ($users as $user)
    <tr class="even pointer">
        <td class=" ">{{ $user->id }}</td>
        <td class=" ">{{ $user->name }}</td>
        <td class=" ">{{ $user->name2 }}</td>
        <td class=" ">{{ $user->email }}</td>
        <td class=" ">{{ $user->birthday }}</td>
    </tr>
    @endforeach
    </tbody>
</table>

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000);
<button id="refresh-btn">Refresh Table</button>
<script>
$(document).ready(function() {
   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }
   $("#refresh-btn").on("click", RefreshTable);
   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });
});
</script>

如何使用jquery/ajax 刷新div中的表内容

使用这个包,它很棒,我一直在使用它。哪一个是datatables.net 的laravel包装器

Github DataTables

使用jQuery的示例。请注意,这只是1000种方法之一。这只是概述了使用AJAX和Laravel构建表的过程的基本思想。这并不意味着它只是代码段中的一个小部分。

基本表代码

<table id="example" class="table">
    <thead>
        <tr class="headings">
            <th>ID &nbsp;&nbsp;&nbsp;</th>
            <th>first name </th>
            <th>last name </th>
            <th>E-mail </th>
            <th>birthday </th>
        </tr>
    </thead>
    <tbody>
        <?php // empty for now ?>
    </tbody>
</table>

tablecontents.blade.php

<?php // Requires the $users table ?>
@foreach ($users as $user)
     <tr class="even pointer">
         <td class=" ">{{ $user->id }}</td>
         <td class=" ">{{ $user->name }}</td>
         <td class=" ">{{ $user->name2 }}</td>
         <td class=" ">{{ $user->email }}</td>
         <td class=" ">{{ $user->birthday }}</td>
     </tr>
@endforeach

AjaxController.php(或类似)

function getUpdatedTable() {
     $users = //get users
     return view("tablecontents", [ "users", $users ]);
} 

JavaScript

function updateTable() {
    $.ajax({
        url: "ajax/getUpdatedTable",
        success: function (data) {
             $("#example tbody").html(data);
        }
    });
}
$(document).ready(function () { 
     updateTable();
     setInterval(updateTable, 5000); //Re-update every 5 seconds     
});

正如评论中提到的,您可以使用jQuery等框架来构建实时模块。

$( document ).ready( function () {
    $.get('generic-handler.php')
        .done( function (data) {
            $('#realtime').innerHTML = data;
        });
});

在PHP文件中,您可以放入代码来显示数据库,然后可以将其封装在setInterval中,因此每隔X秒就会发送一次请求。

文档:

$.get-jQuery
setInterval-JS