[英]refresh datatable after database update
在我的html页面中,我有一个表来显示来自数据库的数据。 我想在更新数据库时刷新数据表,而不刷新所有页面。 我正在使用PHP框架Laravel。
<table id="example" class="table"> <thead> <tr class="headings"> <th>ID </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>
使用这个软件包,它很棒,我一直都在使用它。 这是datatables.net的Laravel包装器
使用jQuery的示例。 请注意,这只是执行此操作的1000种方法之一。 这只是概述了使用AJAX和Laravel构建表的过程的基本思想。 这并不意味着是一个嵌入式代码段。
基本表格代码
<table id="example" class="table">
<thead>
<tr class="headings">
<th>ID </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
秒钟发送一次请求。
说明文件:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.