Make several AJAX calls and fill a Datatable with these calls

2

I'm trying to fill a Datatable with the 87 Star Wars characters, for this I'm doing Ajax calls and I put them in the Datatble, the problem is that the API pulls ten characters using a JSON for each url and I can use rods called to get the 87, what is not how to make calls and fill the datatble with this, here I have the Dtatable with the first 10 characters.

link

    
asked by bojackhorseman99 05.04.2018 в 16:52
source

1 answer

1

I did not find anything similar to a function in javascript that can iterate a base url with different parameters (in this case the pages) but the solution that I offer will solve your problem. As a first step, change your way of starting the Datatable() to be done with a data already loaded. To have all the data together I run them in a ajax() separately that are used as input parameters for the function $.when what you do is wait until all the requests are completed to execute the done where you would concatenate the results and then initialize the Datatable. As an example, I only did pages 1 and 2.

SOen Source: Using when () and Using Concat

$(document).ready(function() {
  var arreglo = ['https://swapi.co/api/people/', 'https://swapi.co/api/people/?page=2'];

  // asigno a una variable  a un ajax unico que sera ejecutado
  var call1 = $.ajax({
    url: arreglo[0]
  });

  var call2 = $.ajax({
    url: arreglo[1]
  });

  // ejecuto el when mandandole de momento los dos ajax y espero la respuesta respectiva 
  // en r1 y r2
  $.when(call1, call2).done(function(r1, r2) {
    // la respuesta que devuelve tiene un formato de lista de tres valosres  siendo el primero
    // el result normal del ajax por eso la data devuelta seria r1[0] en donde entro
    // al atributo results para ser concatenada con los demas result.
    data = r1[0].results.concat(r2[0].results);

    $('#example').DataTable({
      data: data, // aqui inicializo el datatable con la data.
      columns: [{
          data: 'name'
        },
        {
          data: 'height'
        },
        {
          data: 'hair_color'
        },
        {
          data: 'skin_color'
        },
        {
          data: 'gender'
        }

      ]
    });

  });
});
<html>

<head>
  <meta charset="utf-8">
  <title>Proyecto Ambiente</title>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />
  <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.js"></script>
</head>

<body>

  <table id="example" class="display" style="width:100%">
    <thead>
      <tr>
        <th>Nombre</th>
        <th>Altura</th>
        <th>Color de Pelo</th>
        <th>Color de Piel</th>
        <th>Genero</th>

      </tr>
    </thead>

  </table>
</body>

</html>
    
answered by 05.04.2018 / 19:55
source