Joh*_*ley 4 html javascript php jquery datatables
我不确定为什么我的数据表中的数据在排序后消失了。
从用户单击提交按钮时触发的 jQuery 开始:
$('#searchSubmit').on('click', function()
{
var searchbooking = $('#searchbooking').val();
var searchbol = $('#searchbol').val();
$.post('api/search.php', {searchbooking: searchbooking, searchbol: searchbol}, function(data)
{
var obj = JSON.parse(data);
$('#tableBody').empty();
var htmlToInsert = obj.map(function (item)
{
return '<tr><td>'+item.BOL_DATE+'</td><td>'+ item.BOOKING_NUM +'</td></tr>';
});
$('#tableBody').html(htmlToInsert.join(''));
});
});
Run Code Online (Sandbox Code Playgroud)
这是我第一次使用 SQLSRV 编码的 PHP 脚本(我可能会添加):
<?php
if($_POST['searchbooking'] == true || $_POST['searchbol'] == true)
{
$_SESSION['where'] = "";
$searchbooking = stripslashes(str_replace( "'", "''", $_POST['searchbooking']));
$searchbol = stripslashes(str_replace( "'", "''", $_POST['searchbol']));
if($searchbooking != "")
{
if( $_SESSION['where'] != "" ) $_SESSION['where'] .= " AND ";
$_SESSION['where'] = "[BOOKING_NUM] = '".$searchbooking."'";
}
if($searchbol != "")
{
if( $_SESSION['where'] != "" ) $_SESSION['where'] .= " AND ";
$_SESSION['where'] .= "[BOL_NUM] = '".$searchbol."'";
}
$where = "WHERE " . $_SESSION['where'];
$select = "SELECT [BOL_DATE], [BOOKING_NUM] FROM [brokerage].[dbo].[detailbackup] ".$where."";
$query = sqlsrv_query($dbc, $select);
$out = array();
while( $row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC) )
{
$out[] = $row;
}
echo json_encode($out);
?>
Run Code Online (Sandbox Code Playgroud)
回到我的 HTML 页面,表格设置如下:
<table class='table table-striped table-bordered table-hover display nowrap' id='example1' cellspacing="0" width="100%">
<thead>
<tr>
<th>Bol Date</th>
<th>Booking Number</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
在 HTML 页面底部附近,结束正文标记上方,我有格式化 DataTable 的 JavaScript:
<script type="text/javascript">
$('#example1').DataTable({
"iDisplayLength": 25,
"scrollX": true,
"scrollY": 550,
"order": [[ 0, "desc" ]],
"bLengthChange": true,
"bSort": true,
"bAutoWidth": true
</script>
Run Code Online (Sandbox Code Playgroud)
通过上面添加的所有内容,我可以将数据返回到页面。但是一旦我排序(甚至将表的长度从 25 更改为 50),数据就会消失。
有没有人看到我的错误?
您不能以这种方式向数据表添加新行;你必须通过API。您只是向 DOM 表插入新行,而不是 dataTables 内部结构,这就是为什么在排序(或过滤等)时行似乎消失的原因。将 dataTable 实例保存在全局变量中:
table = $('#example1').DataTable({
"iDisplayLength": 25,
...
})
Run Code Online (Sandbox Code Playgroud)
现在重写整个$.post以使用 API 而不是 jQuery DOM 操作:
$.post('api/search.php', {searchbooking: searchbooking, searchbol: searchbol}, function(data) {
table.clear() //clear content
var obj = JSON.parse(data);
obj.forEach(function(item) { //insert rows
table.row.add([item.BOL_DATE, item.BOOKING_NUM])
})
table.draw() //update display
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9202 次 |
| 最近记录: |