jquery datatable get json data from ajax

2019-09-15 20:08发布

问题:

I want to build a datatable from the json data I am getting on the server

    $(document).ready(function() {
        $('#example').DataTable( {

        "ajax": "/analyze/List",
        "columns": [
        { responsedata: "Name" },
        { responsedata: "Total" },
        { responsedata: "Passed" },
        { responsedata: "Failed" }]  

        } );
    } );

Didn't work.Is that not how it's supposed to be done ? .

Here's the json data format on server-

{"responseCode":0,"responseData":[{"Name":"Rocky","Total":39,"Passed":35,"Failed":4}]}

Also, I'm an error Uncaught TypeError: Cannot read property 'length' of undefined. Could someone help ? I'm a noob in this.

回答1:

Yu are doing it a little bit backwards. Use the dataSrc attribute to instruct dataTables that the rows is hold by the responseData property, and refer to each field via the data attribute, not responseData :

$('#example').DataTable({
    ajax: {
        url: '/analyze/List',
        dataSrc: 'responseData'
    },
    columns: [
      { data: "Name" }, 
      { data: "Total" }, 
      { data: "Passed" },
      { data: "Failed" }
    ]
})

demo -> http://jsfiddle.net/2qycjwaz/