Create a Div for each request result

Asked

Viewed 46 times

2

To create a div for each result obtained through a request in an API, the API in use is "https://jsonplaceholder.typicode.com". My intention is to replicate a div "caixaPost" for each obtained result.

var usuarioId = document.getElementById("usuarioId");
var postId = document.getElementById("postId");
var tituloPost = document.getElementById("tituloPost");
var descricaoPost = document.getElementById("descricaoPost");

var idUsuario = document.getElementById("idUsuario");
document.getElementById("botaoBuscaId").onclick = RequisicaoPorUsuario;

function RequisicaoPorUsuario() {

    var HttpClient = function () {
        this.get = function (aUrl, aCallback) {
            var anHttpRequest = new XMLHttpRequest();
            anHttpRequest.onreadystatechange = function () {
                if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                    aCallback(anHttpRequest.responseText);
            }
            anHttpRequest.open("GET", aUrl, true);
            anHttpRequest.send(null);
        }
    }

    //puxa o id do usuário informado
    var usuarioId = idUsuario.value;

    //da um alert pra verificar se ta puxando corretamente
    alert(usuarioId);

    //concatena a url de busca com o ID do Usuário informado
    var url = "https://jsonplaceholder.typicode.com/posts/?userId="+usuarioId;

    var client = new HttpClient();
    client.get(url, function (response) {
        var response1 = JSON.parse(response);
        console.log(response);

        // exibe todos os dados buscados em uma janela de Alert
        alert(response);

        // Aqui eu desejo criar um laço que crie uma janela de post para cada "resultado" obtido...
    });
}
body{
    font-family: 'Open Sans', sans-serif;
}
.caixaPost {
    float: left;
    background-color: rgb(138, 180, 75);
    width: 50%;
    height: auto;
}
.caixaUsuarioId {
    padding: 1%;
    float: left;
    margin: 1%;
    background-color: aliceblue;
}
.caixaPostId {
    padding: 1%;
    width: 50%;
    float: left;
    margin: 1%;
    background-color: aliceblue;
}
.caixaTituloPost {
    padding: 1%;
    width: 96%;
    float: left;
    margin: 1%;
    background-color: white;
}

.caixaDescPost{
    padding: 1%;
    width: 96%;
    float: left;
    margin: 1%;
    background-color: white;
    text-align: justify;
}
<!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">
    <link rel="stylesheet" href="estilo.css">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <title>Teste Estágio - 2019</title>
</head>

<body>
    <button id="botaoBuscaId">Buscar por id</button>
    <input type="text" id="idUsuario">
    <div class="caixaPost" id="caixaPost">

        <div class="caixaUsuarioId">Id Usuário:
            <span id="usuarioId">X</span>
        </div>
        <div class="caixaPostId">Id post:
            <span id="postId">X</span>
        </div>
        <div class="caixaTituloPost">Título:
            <span id="tituloPost">XXX</span>
        </div>
        <div class="caixaDescPost">Descrição:
            <span id="descricaoPost">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's
                standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it
                to make a type specimen book. It has survived not only five centuries, but also the leap into electronic
                typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset
                sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker
                including versions of Lorem Ipsum.</span>
        </div>
    </div>

    <script src="scriptAPI.js"></script>
</body>

</html>

http://jsfiddle.net/5w8bknmc/

2 answers

1

Simple as that baby!

notice how the construction is made:

        // Aqui eu desejo criar um laço que crie uma janela de post para cada "resultado" obtido...
        let element = "";
        for (let index = 0; index < response1.length; index++) {
            element = `
              <div>
                <h1>title: ${response1[index].title}</h1>
                <p>body: ${response1[index].body}</p>
              </div>
            `;

          }
   document.getElementById("divResultado").innerHTML = element;

var usuarioId = document.getElementById("usuarioId");
var postId = document.getElementById("postId");
var tituloPost = document.getElementById("tituloPost");
var descricaoPost = document.getElementById("descricaoPost");

var idUsuario = document.getElementById("idUsuario");
document.getElementById("botaoBuscaId").onclick = RequisicaoPorUsuario;

function RequisicaoPorUsuario() {

    var HttpClient = function () {
        this.get = function (aUrl, aCallback) {
            var anHttpRequest = new XMLHttpRequest();
            anHttpRequest.onreadystatechange = function () {
                if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                    aCallback(anHttpRequest.responseText);
            }
            anHttpRequest.open("GET", aUrl, true);
            anHttpRequest.send(null);
        }
    }

    //puxa o id do usuário informado
    var usuarioId = idUsuario.value;

    //concatena a url de busca com o ID do Usuário informado
    var url = "https://jsonplaceholder.typicode.com/posts/?userId="+usuarioId;

    var client = new HttpClient();
    client.get(url, function (response) {
        var response1 = JSON.parse(response);
        console.log(response1[0]);
        
        // Aqui eu desejo criar um laço que crie uma janela de post para cada "resultado" obtido...
        let element = "";
        for (let index = 0; index < response1.length; index++) {
            element = `
              <div>
                <h1>title: ${response1[index].title}</h1>
                <p>body: ${response1[index].body}</p>
              </div>
            `;
              
          }
   document.getElementById("divResultado").innerHTML = element;

    });
}
body{
    font-family: 'Open Sans', sans-serif;
}
.caixaPost {
    float: left;
    background-color: rgb(138, 180, 75);
    width: 50%;
    height: auto;
}
.caixaUsuarioId {
    padding: 1%;
    float: left;
    margin: 1%;
    background-color: aliceblue;
}
.caixaPostId {
    padding: 1%;
    width: 50%;
    float: left;
    margin: 1%;
    background-color: aliceblue;
}
.caixaTituloPost {
    padding: 1%;
    width: 96%;
    float: left;
    margin: 1%;
    background-color: white;
}

.caixaDescPost{
    padding: 1%;
    width: 96%;
    float: left;
    margin: 1%;
    background-color: white;
    text-align: justify;
}
<!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">
    <link rel="stylesheet" href="estilo.css">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <title>Teste Estágio - 2019</title>
</head>

<body>
    <button id="botaoBuscaId">Buscar por id</button>
    <input type="text" id="idUsuario">
    <div class="caixaPost" id="caixaPost">

        <div class="caixaUsuarioId">Id Usuário:
            <span id="usuarioId">X</span>
        </div>
        <div class="caixaPostId">Id post:
            <span id="postId">X</span>
        </div>
        <div class="caixaTituloPost">Título:
            <span id="tituloPost">XXX</span>
        </div>
        <div class="caixaDescPost">Descrição:
            <span id="descricaoPost">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's
                standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it
                to make a type specimen book. It has survived not only five centuries, but also the leap into electronic
                typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset
                sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker
                including versions of Lorem Ipsum.</span>
        </div>
    </div>
    <div id="divResultado"></div>
    <script src="scriptAPI.js"></script>
</body>

</html>

  • Perfect Julio, the path I am looking for is exactly this, but there is still a problem, it ta listing only the last response of the request. From what I’ve observed he’s running a perfect loop, but when writing the next element he ends up writing the first written element.

1


@Júlio Henrique great answer only that in the section below we must make a slight change to work as expected

        // Aqui eu desejo criar um laço que crie uma janela de post para cada "resultado" obtido...
        let element = ""; // (Antes  let element = "";
        for (let index = 0; index < response1.length; index++) {
            element += ` // (element = `) Dessa forma os itens vão ser acumulados em vez de se sobreescrever
              <div>
                <h1>title: ${response1[index].title}</h1>
                <p>body: ${response1[index].body}</p>
              </div>
            `;

          }

   document.getElementById("divResultado").innerHTML = element;
  • Thanks @Vinicius, one more question, aren’t those "$" dollar bills referring to Jquerry? vetoed the use of Jquerry in the test, if use automatically I am disqualified.

  • If you can’t use jQuery just remove ${} and use response1[index]. * use the character ` before and after concatenating the variable

  • Perfect friend, the syntax went like this, it worked perfectly: var postUserId = Sponse.data[i]. userid; element += &#xA; <div class="caixaUsuarioId">Usuário ID: +postUserId+</div>&#xA; ;

  • Very good friend, success there in your project !

Browser other questions tagged

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