简体   繁体   中英

Why can't jQuery dataTables parse my JSON?

I am trying to populate a dataTable as follows:

$("#my-datatable").dataTable( {
    "sAjaxSource" : "/someURLOnMyServer",
    "bDestroy" : true,
    "fnServerParams" : function(serverParams) {
        serverParams.push(
            {
                "name" : "widget",
                "value" : token
            }
        );
    }
});

And the HTML table it is populating:

<table id="my-datatable">
    <thead>
        <tr>
            <th>Type</th>
            <th>Value</th>
            <th>ID</th>
            <th>Fizz</th>
            <th>Buzz</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

According to Firebug, the JSON coming back from the server is:

[
   {
      "id":1,
      "attributeType":{
         "id":1,
         "name":"test1",
         "tag":"test-type",
         "is-dog":false
      },
      "attributeValue":{
         "id":null,
         "name":"blah",
         "tag":"BLAH"
      },
      "buzz":1,
      "fizz":"53abc"
   }
]

But Firebug is throwing the following JavaScript error in its console:

TypeError: aData is undefined
[Break On This Error]   

for ( i=0 ; i<aData.length ; i++ ) --> jquery.dataTables.js (line 2541)

Can anyone spot what's going wrong? Either I'm not setting up my dataTable object correctly, or the JSON coming back doesn't match the "schema" of the HTML table it is trying to populate. Either way, I'm lost. Thanks in advance!

Datatables requires a certain format for results. If you are not using that format, you have to declare everything.

$('#my-datatable').dataTable( {

    "sAjaxSource": "/url/here",


    "fnServerData": function ( sSource, aoData, fnCallback ) {
            aoData.push( { "name": "widget", "value": "token" } );

            request = $.ajax({
              "dataType": 'json', 
              "type": "GET", 
              "url": sSource, 
              "data": aoData, 
              "success": fnCallback
            });
      },


      "aoColumns": [
            { "mDataProp": "id"},
            { "mDataProp": "fizz"},
            { "mDataProp": "name"},
            { "mDataProp": "tag"},
            { "mDataProp": "tag"},
            { "mDataProp": "attributeValue.name"},
            { "mDataProp": "attributeValue.tag"},
        ],

    });

This is the format: http://datatables.net/release-datatables/examples/server_side/post.html

Try to enclose your JSON object with aaData like:

{"aaData" : 

[{"id":1,"attributeType":{"id":1,"name":"test1","tag":"test-type","is-dog":false},"attributeValue":{"id":null,"name":"blah","tag":"BLAH"},"buzz":1,"fizz":"53abc"}]

}

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