datatables server side population

前端 未结 1 574
后悔当初
后悔当初 2021-01-27 19:02

i have spend several hours trying to find how to populate the datatables with a json that comes from the backend, here is my code:

相关标签:
1条回答
  • 2021-01-27 19:51

    1) Create your datatable on document.ready.

    2) Send a ajax request to get json data.

    3) Inside the loop, instead of creating <tr> elements use datatables fnAddData(); function. like -

    $('#dataTables-example').dataTable().fnAddData([first-columnval, second-columnval, etc]);
    

    I have created a sample

    HTML

    <button id="addData">Add Data</button>
    
    <table id="dataTable" class="display" cellspacing="0" width="100%">
                <thead>
                    <tr>                
                        <th>Id</th>
                        <th>Title</th>
                        <th>Summary</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
    

    JS

     $(document).ready(function() {
     //creating a temp json. you will get this from server side after ajax call 
     var jsonString = '[{"Id": 1,"Title": "Title1","Summary": "Summary1"  },{"Id": 2,"Title": "Title2","Summary": "Summary2"}]';
    
     $("#addData").click(function(){
            var data = JSON.parse(jsonString);
            for(i=0; i<data.length;i++) {
                    $('#dataTable').dataTable().fnAddData([
                    data[i].Id,
                data[i].Summary,
                data[i].Title
            ]);
            }
            //console.log(JSON.parse(jsonString));
     });
    
      function createDatatable() {
        $('#dataTable').dataTable({
            bFilter: false,
            bLengthChange: false,
            "sDom": 'lfrtip',
            pagingType: 'full',
            "oLanguage": {
                "oPaginate": {
                    "sFirst": "<b><<</b>",
                    "sLast": "<b>>></b>",
                    "sNext": "<b>></b>",
                    "sPrevious": "<b><</b>"
                }
            }
        });
    }
    
    createDatatable();
    
    });
    

    Please check this Fiddle

    0 讨论(0)
提交回复
热议问题