Receive Json array and insert into a loop with HTML

Asked

Viewed 1,751 times

2

Good evening, I’m using phonegap to make an app and then I get the following problem:

I have this code in HTML:

<div class="content">   

<article class="underline">
        <a href="incidente.html"><img id="incidente"  
         src="img/buraco.jpg" alt="Incidente" /></a>
        <h2><a href="basic_markup.html" id="tit"></a></h2>
        <p id="desc"></p>
        <div class="date" id="date"></div>
        <img class="tick" alt="não resolvido" src="img/no-tick.png">
        <img class="apoio" alt="apoiar" src="img/apoio.png">

</article>

And this AJAX Code that receives an array from my database:

$.ajax({

  type: "GET",
  url: "http://localhost/again/www/index.php",
  dataType: "json",

  success: function (data) {

    var tit = "";
    var desc = "";
    var date = "";
    // Loop over each object
    for (var $i = 0; $i < data.length; $i++) {
        var object = data[$i];

        tit=  object.titulo;
        desc=  object.descricao;
        date=  object.data;


    }
          $('#tit').html(tit);
          $('#desc').html(desc);
          $('#date').html(date);


 }
});

</script>

I would like the HTML code that I posted above (an article for each line of the database) to be generated for each set of titles, registration and date of the database. Could someone help me?

The Json I get in ajax has this structure:

 [{"codigo":"32","0":"32","titulo":"Assalto na Avenida 2","1":"Assalto      
 na Avenida 2","descricao":"Ontem a noite estava passando pela avenida 
 2 quando 1 rapaz me abordou com uma arma e pediu que eu passasse meu 
 celular. Já é a terceira vez que passo por isso.","2":"Ontem a noite   
 estava passando pela avenida 2 quando 1 rapaz me abordou com uma arma 
 e pediu que eu passasse meu celular. Já é a terceira vez que passo 
 por isso.","data":"2015-10-29 21:48:13","3":"2015-10-29 21:48:13"},
 {"codigo":"59","0":"59","titulo":Roubo na rua 5 ,"1":Roubo na rua  
 5,"descricao":Roubaram minha bolsa com meus pertences,"2":Roubaram 
 minha bolsa com meus pertences,"data":"2015-10-30 
 20:45:46","3":"2015-10-30 20:45:46"}]
  • To make edits among other things it is better to log in again with your account.

  • @user35475, updated my answer to use the structure you posted as an example.

3 answers

2

First thing, I advise you not to use id as identifier within a template, remember that you will have this set of cloned elements and it is not interesting to have two elements with the same id on the page, then use some other value, such as a class or a data-*.

Below follows an alternative using the tag template:

var content = document.getElementById("content");
var tmplItem = document.getElementById("tmplItem");

var data = [
  {
    "codigo": 32,
    "titulo": "Assalto na Avenida 2",
    "descricao": "Ontem a noite estava passando pela avenida 2 quando 1 rapaz me abordou com uma arma e pediu que eu passasse meu celular. Já é a terceira vez que passo por isso.",
    "data": "2015-10-29 21:48:13"
  },
  {
    "codigo": 59,
    "titulo": "Roubo na rua 5",
    "descricao": "Roubaram minha bolsa com meus pertences",
    "data": "2015-10-30 20:45:46"
  }
];

//populando conteudo.
data.forEach(function (dataItem, indice) {
  //clonando conteudo do template.
  var item = document.importNode(tmplItem.content, true);

  //atualizando o novo item com os valores do dataItem atual.
  item.querySelector(".tit").textContent = dataItem.titulo;
  item.querySelector(".desc").textContent = dataItem.descricao;
  item.querySelector(".date").textContent = new Date(dataItem.data).toLocaleString();
  content.appendChild(item);
});
<div id="content">

</div>

<!-- o conteudo deste template será clonado pelo JavaScript -->
<template id="tmplItem">
    <article class="underline">
        <a href="incidente.html">
            <img src="img/buraco.jpg" alt="Incidente" />
        </a>
        <h2>
            <a href="basic_markup.html" class="tit"></a>
        </h2>
        <p class="desc"></p>
        <div class="date"></div>
        <img class="tick" alt="não resolvido" src="img/no-tick.png" />
        <img class="apoio" alt="apoiar" src="img/apoio.png" />
    </article>
</template>

0

Apparently, the only problem is taking and grouping the return of the type JSON, but still the structure of the JSON in use which would further facilitate understanding.

How you’re just returning values, and you’re using jQuery, you can use the getJSON to obtain these values.

As an example, for the script jQuery you would have:

$(document).ready(function(){
    var data = '';
    $.getJSON('getEach.php', function(retorno){
        $.each(retorno, function(chave, valor){
                data += '<article class="underline">';
                data += '<h2><a href="#" id='+ valor.titulo +'>' + valor.titulo + '</a></h2>';
                data += '<p id=' + valor.id +'></p>';
                data += '<div class="date" id='+ valor.id +'></div>';
                data += '</article>';
            });
            $('.content').append(data);
    });
    });

For the structure html in the body of the page, div with class='content' would be basically this:

 <body>
  <div class="content">

  </div>
 </body>

Since you did not specify which values are returned from the database, I took the liberty of creating others:

<?php

//JSON por norma deve possuir o tipo MIME application/json com carateres utf
header('Content-Type: application/json; charset=utf-8');

// Retorno semelhante às colunas do banco de dados.
$data = array(
        array('id'=>20, 'titulo'=>'Primeiro'),
        array('id'=>12, 'titulo'=>'Segundo'),
        array('id'=>8, 'titulo'=>'Terceiro')
             ); 

// Retornar a array no formato JSON          
echo json_encode($data);    

?>  

References:

0

There’s N ways of doing, but always try to avoid writing the method .html() inside the loop, this overloads the method and may not work properly. Note that I output the HTML after the loop FOR:

function viewData(data, el) {

var content='';
for (var i in data) {

 var tit    =data[i].titulo;
 var desc   =data[i].descricao;
 var dateVal=data[i].data;

content+= '<article class="underline">\
            <a href="incidente.html"><img id="incidente"\ src="img/buraco.jpg" alt="Incidente" /></a>\
            <h2><a href="basic_markup.html" id="tit">'+tit+'</a></h2>\
            <p id="desc">'+desc+'</p>\
            <div class="date" id="date">'+dateVal+'</div>\
            <img class="tick" alt="não resolvido" src="img/no-tick.png">\
            <img class="apoio" alt="apoiar" src="img/apoio.png">\
           </article>';
}
$('#'+el).html(content);
}

$(function(){

  $.ajax({
          type: "POST",
          url: "http://localhost/again/www/index.php",
          dataType: "json",
          success: function (data) {
                       viewData(data,'content');
                   }
        });
});

See working here

  • When I try this code you passed, the following error appears: "Uncaught Referenceerror: $ is not defined" pointing to the line: $(Function(){ ?

  • @Ivan Ferrer Solved, in case it was a problem with my Jquery library. Thank you so much for the help!!

Browser other questions tagged

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