使用ajax加载行时,数据表上的任何操作后数据都会丢失

时间:2017-07-11 10:41:33

标签: ajax codeigniter datatable

我从CodeIgniter中的控制器使用dataTable获取Ajax行。

我已成功获取它,但问题是在对sortingsearching这样的dataTable执行任何操作时行丢失了。 但刷新页面后又回来了。

这是我的Ajax脚本:

$('#dataTable_choose').DataTable({
     responsive: true   
});

$('body').on('click', '.getJobApplication', function(e) {

    //alert();

    var noteId = $(this).data('noteId');    
    var note_id = { id : noteId }

     $.ajax({         
    type: 'POST',
    async: true,
    dataType: 'Json',         
    url: get_table_rows,
    data: note_id,
    success: function (response) {                   

        if(response.length > 0){  

        for (i = 0; i < response.length; i++) {   

      innerhtml += "<tr>" +
        "<td>"+response[i].column1+"</td>" +
        "<td>"+response[i].column2+"</td>" +
        "<td>"+response[i].column3+"</td>" +
        "<td>"+response[i].column4+"</td>" +
        "<td><span class='label label-info'>"+column5+"</span></td>" +
        "<td>"+
        "<button type='button' class='btn btn-success waves-effect waves-light' data-secid="+response[i].id2+" " +
        " data-fiid = "+response[i].id+" >Choose</button>" +
        "</td>" +                               
        "</tr>";

        $('#table_body').html(innerhtml);
        }

        } else {
            console.log('error');
        }       

    },
    error: function (msg)
    {
        console.log('error');
    }

 });    

});

这是表HTML代码:

<table id="dataTable_choose" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0"  width="100%">
    <thead>
    <tr>
        <th>Job Title</th>
        <th>Qualification</th>
        <th>Qualification Major</th>
        <th>Candidate Name</th>
        <th>Status</th>
        <th>Action</th>                                    
    </tr>
    </thead>
    <tbody id="table_body">

    </tbody>
</table>

1 个答案:

答案 0 :(得分:1)

使用ajax更改DataTable的内容后,您需要清除DataTable并重绘它。以下代码适用于我(尝试添加您的ID,请验证它们是否正确并在您的代码中正确实施):

success: function (response) {
  //DRAW YOUR innerhtml HERE, as you already do
  $("#dataTable_choose").dataTable().fnClearTable(); //clear the table
  $('#dataTable_choose').dataTable().fnDestroy(); //destroy the datatable
  $('#table_body').html(innerhtml);  //add your new data
  $('#dataTable_choose').DataTable({  //redraw with new data
      //YOUR OPTIONS HERE
  });
});