Datatables - filter data from AJAX source

2019-06-10 16:20发布

问题:

I have a datatable and am fetching the data from an api. Now i have the status like active,inactive if the flag is active then i need to show in the datatble else i should not show the expired one.Here is my fiddle. In this fiddle am showing the active and inactive both. but i want to show only the active status.

HTML

<table id="example" class="display" cellspacing="0" width="100%">
     <thead>
         <tr>
           <th>Name</th>
           <th>Email</th>
           <th>Subject</th>
           <th>Status</th>
           <th>Message</th>
           <th>Details</th>
         </tr>
        </thead>
 </table>

SCRIPT:

$(document).ready(function() {
    $('#example').DataTable({
        "processing" : true,
        "ajax" : {
            "url" : "https://api.myjson.com/bins/12uwp2",
            dataSrc : ''
        },
        "columns" : [ {
            "data" : "name"
        }, {
            "data" : "email"
        }, {
            "data" : "subject"
        }, {
            "data" : "status"
        },{
            "data" : "message"
        },
        {
                "mData": "Details",
                "mRender": function (data, type, row) {
                    return "<a class='delete' data-id=" + row.id + " href='/Details/" + row.id + "'>Delete</a>";
                }
        }]
    });
    $(document).on("click", ".delete", function(e) {
        e.preventDefault()
        alert("Delete button clicked for Row number " + $(this).data("id"))
    })
});

How to do this. Can anyone help me how to do.

回答1:

The use case is: Manipulate the data returned from the server

$('#example').DataTable({
    "ajax" : {
        "url" : "https://api.myjson.com/bins/12uwp2",
        "dataSrc": function ( json ) {
            return json.filter(function(item){
                return item.status=="active";         
                });
         }
    }
});

The key is to use dataSrc properly for data manipulation.

As a function - As a function it takes a single parameter, the JSON returned from the server, which can be manipulated as required. The returned value from the function is what will be used by DataTables as the data source for the table.

I recommend to remove the processing property from DataTable initialization object since there is no heavy processing step anymore.

Docs

  • Load data for the table's content from an Ajax source - Examples
  • Live Example - JSFiddle
  • Clean code example using a separate filter function - JSFiddle