2016-08-09 103 views
0

我使用DataTable。我發送數據到json文件中的數據表單onclick。問題是當我使用$('.datatable-ajax-source table').dataTable().fnDestroy();時,我鬆開了過濾器,行和分頁。我得到的只是像下表:ajax成功後刷新ajax數據表

enter image description here

這是我的機能的研究的javascript:

$('#ButtonPostJson').on('click', function() {   
    var forsearch = $("#searchItem").val(); 
    $.ajax({ 
     processing: true, 
     serverSide: true, 
     type: 'post', 
     url: 'path.json', 
     dataType: "json", 
     success: function(data) { 
      $.each(data, function(i, data) { 
       var body = "<tr>"; 
       body += "<td>" + data.name + "</td>"; 
       body += "</tr>"; 
      $('.datatable-ajax-source table').append(body); 
     }); 

     /*DataTables instantiation.*/ 
     $('.datatable-ajax-source table').dataTable().fnDestroy(); 
    }, 
    error: function() { 
     alert('Fail!'); 
    } 
}); 
}); 

當我更換$('.datatable-ajax-source table').dataTable().fnDestroy();$('.datatable-ajax-source table').dataTable();我得到這個表我想誰

enter image description here

但是當我想要搜索一個新的te rm舊數據仍然存在,我必須手動刷新頁面才能進行新的搜索。我如何刷新或更新我的數據表?

回答

0

我使用fnStandingRedraw刷新服務器端的數據,它的工作原理就像一個魅力(不幸的是,它不推薦使用它)。您可以使用https://datatables.net/plug-ins/api/fnStandingRedraw

var ajaxSourceDataTable; 

//define datatable 
ajaxSourceDataTable = $('.datatable-ajax-source table').dataTable() 

//use this code to redraw/refresh datatable 
ajaxSourceDataTable.fnStandingRedraw(); 
0

你以這種方式使用其丟失的數據表中最好的部分。不要手動構建HTML ...使用.rows.add()(及相關)函數根據需要重繪您的表格。

試試這個:

https://jsfiddle.net/xgpgLydb/

var tbl = $('#example').DataTable({ 
    columns: [{ 
    data: 'Prop1', 
    title: 'Example Prop' 
    },{ 
    data: 'Prop2', 
    title: 'Example Prop 2' 
    }] 
}); 

var req = $.ajax({ 
    url: '/echo/json/', 
    method: 'post', 
    data: { 
     json: JSON.stringify([{ 
      Prop1: 'Foo', 
      Prop2: 'Bar' 
     },{ 
      Prop1: 'Fred', 
      Prop2: 'Flinstone' 
     }]), 
     delay: 1 
    } 
}); 

req.done(function(response) { 
    tbl.rows().remove().draw(); 
    tbl.rows.add(response).draw(); 
});