How to convert the data of ajax (DataTable) in a for cycle?

0

Normally I use ajax and in the .done I do a for for the data that I received to show them in the view of the following way:

for (var i = data.length -1; i >= 0; i--)
            {
                var rowNode = table
                .row.add([  
                            data[i].nombre,
                            data[i].apellido,

                        ])
                    .draw()
               .node();
            }

What happens now is that I do not want to use ajax but clearly the function of datatables but I would not know how to perform a for cycle inside that function to load the data in the data ...

CODE DATATABLES

$(function() {
    var table = $('.row-details-data-table').DataTable({
        "ajax": "../students",
        dom: '<"tbl-top clearfix"lfr>,t,<"tbl-footer clearfix"<"tbl-info pull-left"i><"tbl-pagin pull-right"p>>',
        "columns": [{
            "class": 'details-control',
            "orderable": false,
            "data": null,
            "defaultContent": ''
        }, {
            "data": "name"
        }, {
            "data": "position"
        }, {
            "data": "office"
        }, {
            "data": "salary"
        }],
        "order": [
            [1, 'asc']
        ]
});

I would appreciate a lot ..

    
asked by JDavid 13.03.2017 в 16:11
source

1 answer

0

You could solve it in 2 ways:

  • Format the response of endpoint to the expected format by default:

    {
      "draw": 1, // este dato se envía y se espera que sea devuelto como parte de las respuesta
      "recordsTotal": 57, // (Opcional) Registros en filtrados (eg "data.length")
      "recordsFiltered": 57, // (Opcional) Total de registros (si la respuesta está paginada)
      "data": [{...}] // Arreglo con los registros
    }
    

    See example

  • Another option is to use ajax.dataSrc

  

[...] dataSrc provide the ability to alter what data the DataTables will read from the return JSON from the server [...]

Example:

var table = $('.row-details-data-table').DataTable({
  ajax: {
    url: '../students',
    dataSrc: function(data) {
       return {
         data: data
       };
    }
  },
  dom: '<"tbl-top clearfix"lfr>,t,<"tbl-footer clearfix"<"tbl-info pull-left"i><"tbl-pagin pull-right"p>>',
  columns: [{
    "class": 'details-control',
    "orderable": false,
    "data": null,
    "defaultContent": ''
  }, {
    "data": "name"
  }, {
    "data": "position"
  }, {
    "data": "office"
  }, {
    "data": "salary"
  }],
  order: [
    [1, 'asc']
  ]
});
    
answered by 13.03.2017 в 16:34