jquery - 如何使用数据表将 ajax 结果附加到模态中
问题描述
今天是个好日子!我正在尝试将我的 ajax 结果附加到我的模式内的数据表中。我已经获得了我需要的数据,但它仍然显示数据不可用。
这是我处理结果的ajax成功。
success: function(result)
{
//console.log(result);
//$('#viewTable').empty();
$.each(result, function(index, value){
console.log(value);
$('#viewTable').append(
'<tbody>' +
'<tr>' +
'<td>' + value.qr_code + '</td>' +
'<td>' + value.reference_no + '</td>' +
'<td>' + value.brand_name + '</td>' +
'<td>' + value.model_name + '</td>' +
'<td>' + value.unitPrice + '</td>' +
'</tr>' +
'</tbody>'
);
});
这是我的 HTML
<table id="viewTable" class="table table-striped">
<thead>
<tr>
<th>Barcode</th>
<th>Reference Number</th>
<th>Brand Name</th>
<th>Model Name</th>
<th>Unit Price</th>
</tr>
</thead>
</table>
注意:当我取消注释“$('#viewTable').empty();” 功能它将删除我的thead(数据表)。
谢谢!
解决方案
首先将dataTable对象存储在一个变量中,
var dataTable = $("#viewTable").DataTable();
然后在 ajax 成功时,使用 dataTable.add([" "," ", " "]).draw(),其中 dataTable 是变量名。
要清除数据表,请使用 dataTable.clear();
dataTable.clear().draw();
请参阅下面的代码;
success: function(result) {
// store your data table object in a variable
var dataTable = $("#viewTable").DataTable();
/////////////////////////////////////////////
dataTable.clear().draw();
$.each(result, function(index, value) {
console.log(value);
// use data table row.add, then .draw for table refresh
dataTable.row.Add([value.qr_code, value.reference_no, value.brand_name, value.model_name, value.unitPrice]).draw();
});
}
推荐阅读
- laravel - laravel elasticsearch 只是从第一个模型中搜索
- javascript - 在正则表达式中使用动态数据
- postgresql - 包含 pgAdmin 4 v2.1 的 PostgreSQL 版本是什么?
- html - “在资源包中定义此标签”错误 sonarqube
- javascript - puppeteer 在运行所有笑话测试之前关闭浏览器
- raspberry-pi - 树莓派上的电子透明窗口(4)
- r - 如何在“df2”中添加一个变量,该变量使用“dplyr”或“data.table”指定来自“df1”的变量的特定级别的行数
- css - 为什么我的 CSS 变量会添加注释标记?
- scala - 使用多个火花窗是一件坏事吗?
- ethereum - Remix IDE 出现错误“请在文件资源管理器中选择可以找到合约元数据的文件夹”