简体   繁体   中英

Creating datatables from Javascript source

I am trying to build a datatable (1.10.7) based on an input of a javascript var filled with JSON data. While I've successfully used datatables with ajax sources, I've never attempted to just provide my own variable, but I need to in this case.

Here's my variable:

json = [
 {"dateReceived":"2015-01-01","designCustomer":"MULTITEST 1","designCustomerLocation":"SUNNYVALE, CA"},
 {"dateReceived":"2016-04-05","designCustomer":"MULTITEST 2","designCustomerLocation":"SUNNYVALE, CA"},
 {"dateReceived":"1982-04-18","designCustomer":"MULTITEST 3","designCustomerLocation":"SUNNYVALE, CA"}
 ]

According to DataTables' page on Javascript-Sourced Data ,

This is achieved using the dataDT option in the initialisation object, passing in an array of data to be used (like all other DataTables handled data, this can be arrays or objects using the columns.dataDT option).

I'm confused by the differences in their test string, and in mine:

var dataSet = [
    ['Trident','Internet Explorer 4.0','Win 95+','4','X'],
    ['Trident','Internet Explorer 5.0','Win 95+','5','C'],
    ['Trident','Internet Explorer 5.5','Win 95+','5.5','A'],
    ['Trident','Internet Explorer 6','Win 98+','6','A'],
    ['Trident','Internet Explorer 7','Win XP SP2+','7','A']

Namely, their test variable doesn't contain field names , while mine does.

Here is the code that I've written to try and parse my variable, json :

var table = $('#ltc-table').DataTable( {    
    "data" : json,        
    "columns" : [
      { "title" : "designCustomer" },
      { "title" : "designCutomerLocation" },
      { "title" : "dateReceived" },
  ],
  "lengthMenu": [ 25, 50, 101 ],
  "oLanguage": {
  "sSearch": "Filter Results: "
  }
});

It seems, based on the page I linked above, that I'm doing this correctly, but I'm getting errors instead:

Uncaught Error: DataTables warning: table id=ltc-table - Requested unknown parameter '0' for row 0.

Any tips?

If you want to use objects as data source instead of arrays, you need to bind the columns using the columns.data options:

json = [
 {"dateReceived":"2015-01-01","designCustomer":"MULTITEST 1","designCustomerLocation":"SUNNYVALE, CA"},
 {"dateReceived":"2016-04-05","designCustomer":"MULTITEST 2","designCustomerLocation":"SUNNYVALE, CA"},
 {"dateReceived":"1982-04-18","designCustomer":"MULTITEST 3","designCustomerLocation":"SUNNYVALE, CA"}
];

var table = $('#ltc-table').DataTable( {    
    "data" : json,        
    "columns" : [
      { "data" : "designCustomer" },
      { "data" : "designCustomerLocation" },
      { "data" : "dateReceived" }
  ],
  "lengthMenu": [ 25, 50, 101 ],
  "oLanguage": {
  "sSearch": "Filter Results: "
  }
});

See demo

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