Fill a list with contents of an Api

0

I'm trying to fill a list of characters from an Api, but I have a question about how to fill the array, I had difficulties just having 10 characters and that these are listed and generate a link to a movie . So far I have the API call, but I only print the Json in the console, having created a connection with the html

function ajax_get(url, callback) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.status == 200) {
            console.log('responseText:' + xmlhttp.responseText);
            try {
                var data = JSON.parse(xmlhttp.responseText);
            } catch(err) {
                console.log(err.message + " in " + xmlhttp.responseText);
                return;
            }
            callback(data);
        }
    };

    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

ajax_get("https://swapi.co/api/people/", function(data) {

    var html = "<h2>" + data["title"] + "</h2>";
    html += "<h3>" + data["description"] + "</h3>";
    html += "<ul>";
       for (var i=0; i < "https://swapi.co/api/people/10"; i++) {
           html += '<li><a href="' + data["people"][i]["name"] + '">' + data["people"][i]["mass"] + "</a></li>";
       }
    html += "</ul>";
    document.getElementById("text").innerHTML = html;
});

I appreciate the attention

    
asked by Bella 01.02.2018 в 07:52
source

4 answers

2

The truth that you should check well what you wanted, there were many things that do not make sense, on the one hand you are trying to read properties of json that returns the api that do not exist, you should check the structure, and then you have a for whose condition is that a number is less than a string , which does not make any sense.

I have made certain changes in the code and I have been commenting on them, check it out.

function ajax_get(url, callback) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.status == 200) {
    
            try {
                var data = JSON.parse(xmlhttp.responseText);
            } catch(err) {
                //console.log(err.message + " in " + xmlhttp.responseText);
                return;
            }
            callback(data);
        }
    };

    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

ajax_get("https://swapi.co/api/people/", function(data) {
    
    //La llamada a la api, te devuelve un json con un atributo "results" que es donde vienen los personajes en forma de array, los guardamos en una variable
    var persons=data.results;
  
    //La propiedad data["title"] no existe en el json que recibes
    //var html = "<h2>" + data["title"] + "</h2>";
    var html = "<h2>Lista de personajes</h2>";
    //La propiedad data["description"] tampoco existe en el json que recibes
    //html += "<h3>" + data["description"] + "</h3>";
    html += "<h3>Esta es mi lista de personajes personalizada</h3>";
    html += "<ul>";
       //Este for no tiene sentido, estas haciendo un bucle en el cual la condicion es que un numero sea menor a un string, lo que debes hacer es recorrer el array de persons que hemos creado mas arriba
       //for (var i=0; i < "https://swapi.co/api/people/10"; i++) {
       for(var index in persons){
          //Recojemos cada personaje
          let person=persons[index];
          //Lo añadimos a la variable html sus datos
          html += '<li><a href="' + person.url + '">' + person.name + "</a></li>";
       }
    
    html += "</ul>";
    document.getElementById("text").innerHTML = html;
});
<html>
 <body>
  <div id="text"></div>
 </body>
</html>
    
answered by 01.02.2018 / 10:12
source
2

Good, I also see strange things in the function ajax_get and in the for loop when you call the function. I leave an approach, hopefully it helps. In the commented% console.log you will see what the server returns to you

Greetings

function ajax_get() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open('GET', 'https://swapi.co/api/people/', true);
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState === 4) {
      if (xmlhttp.status === 200) {
        getResult(xmlhttp);
      }
    }
  };
  xmlhttp.send(null);
}

function getResult (xhr) {
  var array = JSON.parse(xhr.response);
  //console.log(array);

  for (var i = 0; i < array.results.length; i++) {
    var p = document.createElement('p');
    document.body.appendChild(p);
    p.innerText = i+1 + '.- ' + array.results[i].name;
  }
}

ajax_get();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<script src="main.js"></script>
</body>
</html>
    
answered by 01.02.2018 в 19:57
1

Nose if I have understood it well but just what you need is to travel the Json and go read it.

$.each( data, function( key, val ) {
    items.push( "<li id='" + key + "'>" + val + "</li>" );
});

Here you can find the most detailed solution , if not you need me to give you more information about your problem.

Greetings

    
answered by 01.02.2018 в 09:27
1

I think this line is not correct:

for (var i=0; i < "https://swapi.co/api/people/10"; i++)

you are conditioning an integral with a text string, if I am not wrong for (var i=0; i < "https://swapi.co/api/people/10"; i++) does not do anything as it is at that moment.

    
answered by 01.02.2018 в 09:50