Can't get DataTables ajax call to work

2019-03-04 21:20发布

问题:

I'm trying to figure out how to use the ajax option in DataTables 1.10. For the life of me, I cannot figure out how it works.

My server-side request, when queried, responds with an object, one element of which is an array that matches my table's column layout. The initialization code I'm using is:

$("#history-table").DataTable({
    'ajax': {
        'url': "/some-path-here",
        'type': "POST",
        'data': { 'pid': pID } // Some data that the server needs
    },
    'columns': [
        { data: 0},
        { data: 1},
        { data: 2},
        { data: 3},
        { data: 4},
        { data: 5}
    ],
    'dataSrc': 'history',
    'autoWidth': false,
    'lengthChange': false,
    'ordering': false,
    'pageLength': 50
});

The object returned by my AJAX call looks like the following (each element is a string):

{
    'success': True,
    'history': [
        ["John Doe", "02 Mar 2016", "Area 1", "Value A", "May 15", "200"],
        ["Jane Doe", "29 Feb 2016", "Area 2", "Value B", "Apr 15", "100"],
        [ ... ]
    ]
}

My server side logic is processing and returning properly, but I get an unhelpful error message from the minified DataTables code:

TypeError: f is undefined

How can I figure out what my real problem is? Is there something obvious I'm missing? The DataTables documentation isn't very helpful, as all of their AJAX examples seem to pull from a text file.

回答1:

  • Option dataSrc should be a sub-property of ajax option.
  • There is no need to specify columns if data elements appear in sequential order
  • Your JSON response appears to be invalid. Correct response should be

    {
      "success": true,
      "history": [
        ["John Doe","02 Mar 2016","Area 1","Value A","May 15","200"],
        ["Jane Doe","29 Feb 2016","Area 2","Value B","Apr 15","100"]
      ]
    }
    

Corrected code is shown below:

$("#history-table").DataTable({
    'ajax': {
        'url': "/some-path-here",
        'type': "POST",
        'data': { 'pid': pID },
        'dataSrc': 'history'
    },
    'autoWidth': false,
    'lengthChange': false,
    'ordering': false,
    'pageLength': 50
});

See this jsFiddle for code and demonstration.