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>