Create and populate elements with json return in jquery

Asked

Viewed 155 times

0

Good night, you guys.

I need to take a json return and mount an html with the data dynamically. I got to the part where I can get the json and nothing else, I’m stuck.

$.ajax({
    type: "get",
    url: "products.json",
    dataType: "json",
    success: function (data) {
        $(data.cart.item).each(function (index, product) {
            
        })
    }
});
<div class="hide-scroller">
                <div class="hide-product">
                    <img class="hide-img" src="img/note-gamer-acer-160-160.jpg" alt="">
                    <div class="colum-product">
                        <p id="name">Notebook Gamer Acer</p>
                        <p id="quant">Qtd.: 1 <span id="total">R$ 7.158,21</span></p>
                    </div>
                </div>
            </div>

1 answer

0

You have several ways to do this. Using the Github API repositories, we can make an example:

const API_URL = 'https://api.github.com/users/lffg/repos?sort=updated';

function generateHTML(data) {
  const repositories = data;
  const $list = $('.list');

  for (const repository of repositories) {
    // Criamos um elemento `<a>`, adicionamos o texto e alguns atributos:
    const $item = $('<a>');
    $item.css('display', 'block');
    $item.text(repository.name);
    $item.attr('href', `https://github.com/${repository.full_name}`);

    // Inserimos o elemento que criamos acima (o `<a>`) na lista.
    $list.append($item);
  }
}

$.ajax({
  type: 'get',
  url: API_URL,
  dataType: 'json',
  success: generateHTML
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="list">
  <!-- Os itens serão adicionados aqui dinâmicamente. -->
</div>

In the above example, how the Github API returns a JSON structure as follows:

[
  { /* Objeto de um repositório. */ },
  { /* Objeto de outro repositório. */ },
  // ...
]

We must iterate over each element of the array. That’s why we have the following statement:

const repositories = data;

If you have a JSON more or less like this:

{
  "items": [
    { /* Objeto de um repositório. */ },
    { /* Objeto de outro repositório. */ },
    // ...
  ]
}

Should the section highlighted above for:

const repositories = data.items;

To learn more about this notation, read property advisors on MDN.


If you want to elaborate a template a little more advanced, you can use the strings template. I also leave an example with a slightly more complex HTML:

const API_URL = 'https://api.github.com/users/lffg/repos?sort=updated';

function generateHTML(data) {
  const repositories = data;
  const $list = $('.list');

  for (const repository of repositories) {
    const $item = $(`
      <div class="item">
        <strong>${repository.name}</strong>
        <em>Linguagem: ${repository.language}</em>
        <a href="https://github.com/${repository.full_name}" target="_blank">
          Link ->
        </a>
      </div>
    `);

    // Inserimos o elemento que criamos acima na lista:
    $list.append($item);
  }
}

$.ajax({
  type: 'get',
  url: API_URL,
  dataType: 'json',
  success: generateHTML
});
.item {
  border: solid 1px #555;
  margin-bottom: 1rem;
  padding: 5px;
}

.item > * {
  display: block;
}

.item > strong {
  font-family: monospace;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="list"></div>

Browser other questions tagged

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