How to export all rows from Datatables using Ajax?

前端 未结 12 1209
广开言路
广开言路 2020-11-29 23:38

I am using new feature in Datatables: \"HTML5 export buttons\". I am loading data with Ajax.

https://datatables.net/extensions/buttons/examples/html5/simple.html

12条回答
  •  一个人的身影
    2020-11-29 23:52

    Yes, it's totally possible to make this work. Internally, DataTables has a function called buttons.exportData(). When you press a button, this function is called and returns the current page content. You can overwrite that function so it pulls all server side results based on current filters. And calling the same url used for ajax pagination.

    You overwrite it before initializing your table. The code is as follows:

    $(document).ready(function() {
    
        jQuery.fn.DataTable.Api.register( 'buttons.exportData()', function ( options ) {
                if ( this.context.length ) {
                    var jsonResult = $.ajax({
                        url: 'myServerSide.json?page=all',
                        data: {search: $(#search).val()},
                        success: function (result) {
                            //Do nothing
                        },
                        async: false
                    });
    
                    return {body: jsonResult.responseJSON.data, header: $("#myTable thead tr th").map(function() { return this.innerHTML; }).get()};
                }
            } );
    
        $("#myTable ").DataTable(
            {
                "dom": 'lBrtip',
                "pageLength": 5, 
                "buttons": ['csv','print', 'excel', 'pdf'],
                "processing": true,
                "serverSide": true,
                "ajax": {
                    "url": "myServerSide.json",
                    "type": 'GET',
                    "data": {search: $(#search).val()} 
                }
            }
    });
    

提交回复
热议问题