How to get Json data from several urls to render a single DataTable

1

I have two URLs that serve data of objects in JSON format, both formats have the same structure, except for the type of equipment:

First URL: link

{
    "id": 1,
    "tipo_equipo": "EquipoA", ///Esto es diferente al otro
    "nomenclatura": "0501",
    "etiqueta": "Sin Eqtiqueta",
    "rack": "1"
} 

Second URL: link

{
    "id": 1,
    "tipo_sw": "ADCDi-R2CU1", ///esto es diferente al de arriba
    "nomenclatura": "0802",
    "etiqueta": "Sin Etiqueta",
    "rack": "145"
}

I would like to render a DataTable with the data of the two urls so that I can display a single table.

$(document).ready(function($) {
$('#dataTables-example').DataTable({                  
    ajax: {
        url: '/api/switch/?rack='+{{pk3}},
  //////url: '/api/equipos/?rack='+{{pk3}},
        dataSrc: '',
        dataType: 'json',

    },
    columns:[
        {"data":"tipo_equipo"}, /////{"data":"tipo_switch"},
        {"data":"nomenclatura"},
        {"data":"etiqueta"},
        {"data":"rack"},
        {"data":"id"},
   ],

 });

});

Can you please support me? Greetings.

    
asked by Rocke 16.08.2016 в 12:11
source

1 answer

1

You should make the two ajax requests separately, collect the received data and apply them to the DataTable object.

Look at this example. First it makes the request for the software data and with the results calls the function "dataSoftware". This function transforms the result to replace the property "type_sw" with "type_quipment" and makes the request to recover the data of equipment. With the result of this request, you join the two data sets and assign them to the DataTable:

$(document).ready(function($){
  
  // 
  function datosSoftware(softData){
    // cambia la propiedad tipo_sw por tipo_equipo
    var tableData = softData.map(function(data) { 
        return {
          id: data.id, 
          tipo_equipo: data.tipo_sw, 
          nomenclatura: data.nomenclatura, 
          etiqueta: data.etiqueta, 
          rack: data.rack
        });
   // Realiza la petición de datos de equipos y carga el DataTable
    $.ajax({
      method: 'GET',
      url: '/api/equipos/?rack=' + {{pk3}},
      dataType: 'json'
      }).done(function(equipmentData){
        // Concatena los resultados
        tableData = tableData.concat(equipmentData);
        // Carga el DataTable
        $('#dataTables-example').DataTable({
            data: tableData,
            columns: [
              {"data": "tipo_equipo"},
              {"data": "nomenclatura"},
              {"data": "etiqueta"},
              {"data": "rack"},
              {"data": "id"}
          ]});
        });
  }
  
  // Realiza la petición de datos de software y llama a datosSoftware
  $.ajax({
      method: 'GET',
      url: '/api/switch/?rack=' + {{pk3}},
      dataType: 'json'
    }).done(datosSoftware);
  
});
    
answered by 16.08.2016 / 12:55
source