如何在带有数据表的模态中附加ajax结果

今天是个好日子! 我试图将我的ajax结果附加到我的模态中的数据表中。 我已经获得了我需要的数据,但它仍然显示数据不可用。

它显示如下: 它显示这样。

这是我的ajax成功处理结果。

success: function(result) { //console.log(result); //$('#viewTable').empty(); $.each(result, function(index, value){ console.log(value); $('#viewTable').append( '' + '' + '' + value.qr_code + '' + '' + value.reference_no + '' + '' + value.brand_name + '' + '' + value.model_name + '' + '' + value.unitPrice + '' + '' + '' ); }); 

这是我的HTML

  
Barcode Reference Number Brand Name Model Name Unit Price

注意:当我取消注释“$(’#viewTable’)。empty();” 它将删除我的thead(Datatable)。

谢谢!

首先将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(); }); } 

标记添加到HTML代码中,如下所示,

  
Barcode Reference Number Brand Name Model Name Unit Price

然后直接附加到tbody

  $('#viewTable > tbody').append( '' + '' + value.qr_code + '' + '' + value.reference_no + '' + '' + value.brand_name + '' + '' + value.model_name + '' + '' + value.unitPrice + '' + '' + ) 

所以我不确定你是否使用了这里找到的DataTable jQuery插件: https : //datatables.net/

它几乎就像你一样。 我喜欢这个插件,如果你不使用它,我肯定会建议你使用它。 这是一个很棒的工具。 它允许我避免使用.each.append作为插件为我处理迭代。

所以你已经建立了你的html表格,所以我不需要覆盖它。 因此,假设您要调用数据,我将继续使用您在问题中使用的数据点,以免混淆您。 在我们开始之前,让我们确定一些事情,确保你的表格的模态是隐藏的。 我个人使用bootstrap模态,因为它们快速而简单。 请注意我使用AJAX速记,希望这不会让你感到困惑,但概念完全相同。 获取您的数据 – >成功时,使用它做一些事情。

 // our html modal will have an id of mymodal // wait for page to load $(document).ready(()=> { // pretending that we have a form and you are searching by that... let refnum = $("#refnum").val() $("#dataform").submit((event)=> { $.get("data.php?referencenumber=" + encodeURIComponent(refnum), (data)=> { console.log(data) $("#viewTable").DataTable({ destroy: true // allows for table to be reloaded with new data SUPER IMPORTANT! data: data, columns: [ // data tables iterating through the data for you {'data': 'barcode'}, {'data': 'referencenumber'}, {'data': 'brandname'}, {'data': 'modelname'}, {'data': 'unitprice'}, ] }); // display hidden modal with data table. You will need to adjust the size of the modal according to how you see fit in CSS. $("#mymodal").slideDown(300); }); event.preventDefault(); }); }); 

我希望这可以帮助你。