html javascript list json data in ul li [closed]

0

Staff ask for help from friends:

The code makes an ajax request to take data from an api (json) and go through all objects inside the array

  

My json = [{Name: "Ajato 2000"}, {Name: "Crystal I"}]

In the case how do I list or print the data with html using a list attribute I know how to do this with php plus with html I know that and type so

  

document.getElementById ('display'). value;

<!DOCTYPE html>
<html>
<body>



<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script><script>$.ajax({type:"POST",
  dataType: "json",
  url: "https://coarinet.com/kibarcos/api",
  success: function(data) {


   
  for (var i in data) { 

  Nomes= data[i]["Nome"];

}



  }
});
</script>
	
<p id="id_nome"></p>
</body>
</html>
    
asked by anonymous 27.11.2018 / 03:51

1 answer

3

From what I understand you will receive a JSON object and want to display it within a list, correct?

So you can do something like this.

let nomes = document.getElementById('nomes')
const listaNomes = [
  { nome: 'Eduardo' },
  { nome: 'José' },
  { nome: 'Ribeiro' },
  { nome: 'Soares'}
]

listaNomes.forEach(obj => {
  nomes.innerHTML += '<li>${ obj.nome }</li>'
})
<ul id="nomes"></ul>

By explaining a little, create a ul tag with a id any, in this case I put it as nomes .

I assumed that the JSON that you get is something like listaNomes , so it's just a loop of repetition, it could be for , while , map and etc, however I chose forEach e then just use innerHTML in ul , which will inject the code inside your tag.

Note: ${} - > is a new JavaScript feature known as template string , which is nothing more than a way to concatenate strings. You can learn more HERE

    
27.11.2018 / 11:27