How to load a table using ajax from datatables?

Asked

Viewed 1,261 times

3

I’m trying to load a table using the component datatables.

The return of this ajax request is a json object in this format:

data = {
  "CLIENTES": {
    "0": {
      "ID": "1",
      "NOME": 'GABRIEL'
    },
    "1": {
      "ID": "2",
      "NOME": 'RODRIGUES'
    }
  }
}

In the documentation Columns data is quoted that the following structure should be created:

table.DataTable({
  "ajax": url,
  columns: [
    {"data": "CLIENTES.ID"},
    {"data": "CLIENTES.NOME"}
  ]
});

But the access to indexes is not performed correctly, in this case should be accessed:

{"data": "CLIENTES['0'].ID"},
{"data": "CLIENTES['1'].ID"},

Dynamically, how could I do this ?

There is a related question that also did not solve my doubt: Load table with json using datatables

1 answer

2


I just recreated the array by removing CLIENTS using the function $.map.

Solution:

$(document).ready(function() {
    data = {
      "CLIENTES": {
        "0": {
           "ID": "1",
           "NOME": 'GABRIEL'
        },
       "1": {
           "ID": "2",
           "NOME": 'RODRIGUES'
         }
       }
     };


   var newData = $.map(data.CLIENTES, function(el) { return el });

   $('#example').DataTable({
       data: newData,
       columns: [
       {"data": "ID"},
       {"data": "NOME"}
       ]
    });

});

See working on jsfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.