Receive Json array and insert into a loop with HTML

2

Good evening, I'm using phonegap to make an application and then the following problem occurred:

I have this HTML code:

<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 for each set of title, description, and date of the database to be generated the HTML code I posted above (an article for each row in the database). can anybody help me?

The Json that 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"}]
    
asked by anonymous 09.11.2015 / 04:14

3 answers

2

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

Below is an alternative using the template tag:

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>
    
09.11.2015 / 13:02
0

It seems that the only problem is to pick up and group the return of type JSON , but the structure of the JSON in use was not presented, which would facilitate even more understanding.

As you are simply returning values, and you are using jQuery , you can use getJSON to get these values.

As an example, for the jQuery script:

$(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 html structure in the body of the page, div with class='content' would basically be 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:

09.11.2015 / 07:03
0

There are N ways to do this, but always try to avoid writing the .html() method inside the loop, this overloads the method and may not work properly. Note that I gave the output in the HTML after the FOR tag:

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

    
09.11.2015 / 17:06