Jquery DataTables : Not able to make dynamic header

时间:2015-06-26 09:30:35

标签: jquery json datatable datatables

Have 2 JSON files

JSON1

callback({
"docs":[
      {
        "A":"qwe",
        "B":"asd",
        "C":"zxc",
        "D":"mnb",
      }]
  })

JSON2

callback({
    "docs":[
          {
            "1":"123",
            "2":"456",
            "3":"789",
            "4":"012",
          }]
      })

Reading JSON file and displaying it in a table using Jquery DataTables plugin.

I want "A","B","C","D" and "1", "2", "3", "4" to be used as table headers or column names

Each Json file is called based on different check box click, as there is different column headers for each JSON i want columns/table headers to be dynamic.

Here is my Datatable initialization

var table = $('#example').DataTable({
                            "data": items,
                            "aoColumns": columns,
                            "scrollX": true,
                            "bAutoWidth": true,
                            });

items variable contains parsed json data which is passed to data and i am able to get the data rendered in table

columns variable contains parsed JSON column names and i am passing it to "aoColumns" but i am not getting the dynamic header values

Have defined a default table header, for any request i am getting default header instead of respective dynamic header.

Please let me know if i am missing anything

Thanks in advance...!!!

1 个答案:

答案 0 :(得分:0)

It might just be easier for you to re-initialize the table from the beginning if you want to change the data and columns definition.

Use $('#example').dataTable().fnDestroy(); and then call your initialization code with the different items and columns variables.

Here is also another way to do this, documented on the datatables plugin website (in this case they use the .destroy() instead of .fnDestroy() but they're essentially the same thing, just in different code setups):

https://datatables.net/reference/api/destroy()