Datatables - filter data from AJAX source

一个人想着一个人 提交于 2020-01-03 04:46:09

问题


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


来源:https://stackoverflow.com/questions/55000320/datatables-filter-data-from-ajax-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!