简体   繁体   中英

jQuery DataTables loading a client-side array of objects

I'm using the.data() function in jQuery to attach a set of records, returned from the server, to a DOM element on my page. The records are stored as an array of Objects. The code is as follows:

    //Attached returned data to an HTML table element
    $('#measTable').data('resultSet', resultSet);

    //Get stored data from HTML table element
var results = $('#measTable').data('resultSet');

//Construct the measurement table
data_table = $('#measTable').dataTable({
    "bJQueryUI": true,
    "sPaginationType": "full_numbers",
    "bProcessing": true,
    "bDeferRender": true,
    "aaData": [ results ],
    "aoColumns": [
                { "mDataProp": "Field1" },
                { "mDataProp": "Field2" },
                { "mDataProp": "Field3" },
                { "mDataProp": "Field4" }
            ]
});

I then fetch the data from the element and proceed to load it into the datatable. But this doens't seem to work and always returns with the error Requested unknown parameter "`Field1" from the data source at row 0 . Is it possible to load data into datatables in this manner?

UPDATE:

Here is a sample of the result object array

results = 
    0: Object
       Field1: "2011/04/23"
       Field2: 8
       Field3: "Hello"
       Field4: "World"
       __proto__: Object
    1: Object
       Field1: "2011/03/25"
       Field2: 6
       Field3: "Hello"
       Field4: "Everyone"
       __proto__: Object
...etc.

Allan, the developer of DataTables, was able to answer my question in the following post in the DataTables forum . In case the link doesn't work, the issue turned out to be a simple syntax error.

Instead of "aaData": [ results ], it needs to be "aaData": results, .

Thank you for your help Allan.

Well, aaData (as it name suggests using hungarian notation ) expects an array of arrays, so if you fetch him an array of objects that is why it complains.

Add to your definition the following:

$('#measTable').dataTable({
    ...
    "columns": [
        { "data": "field1" },
        { "data": "field2" },
        { "data": "field3" }
    ]
});

You should match the table columns with the columns array.

That's it!

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