繁体   English   中英

数据库更新后刷新数据表

[英]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数据表

使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM