简体   繁体   中英

jQuery dataTable sort with ajax loaded data

I have several rows that include some lazy loaded data. For instance,

  <table border="1"> <tr> <th>Employee</th><th>Sales</th> </tr> <tr> <td>Michale</td><td>1000</td> </tr> <tr> <td>Kim</td><td id="kimSales"></td> </tr> <tr> <td>John</td><td id="johnSales"></td> </tr> </table> 

The problem is, I have to retrieve some data after page loaded because of some reasons. Let's suppose kimSales is 1500 , and johnSales is 2500 .

<script>
    $(document).on('ready', function(e){
         $('#kimSales').text(1500);
         $('#johnSales').text(2500);
    })     
</script>

In this situation, I want to sort properly with lazy loaded data. You know, jQuery dataTable has sorting features through click header of columns, like https://datatables.net I couldn't sort these data properly. The sorted data is not ascending, or dsc --- maybe dataTable couldn't recognize after loaded data.

What I tried :

<script>
    $(document).on('ready', function(e){
         $('#kimSales').text(1500);
         $('#johnSales').text(2500);
    })

    table.dataTable(); // not properly working
</script>

If you update cell's data BEFORE initializing the table, it should work correctly.

Also you should be initializing the table in ready event handler. For example:

$(document).on('ready', function(e){
     $('#kimSales').text(1500);
     $('#johnSales').text(2500);

     var table = $('#example').DataTable();
});

If you update cell's data AFTER initializing the table, you need to use cell().invalidate() API method and redraw the table.

For example:

$(document).on('ready', function(e){
     var table = $('#example').DataTable();

     $('#kimSales').text(1500);
     table.cell($('#kimSales').closest('td')).invalidate();

     $('#johnSales').text(2500);
     table.cell($('#johnSales').closest('td')).invalidate();

     table.draw();
});

I hope you want to achieve sorting based on the second column. Try this in the table initialization code and with your preferred sorting technique [asc,desc]

 $('table').DataTable( {
        "order": [[ 1, "desc" ]]
    } );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM