0
I need to take data in JSON, display it and do searches, for that I developed this code, but I have problem to put this data in external file. How can I put this JSON in an external file, keeping the same current structure without using Jquery?
Javascript code:
var content = document.getElementById("content");
var tmplItem = document.getElementById("templatePost");
var search = document.getElementById("search");
var database = [
{
"id": 1,
"nome_jogo": "Jogo 1",
"url_jogo": "jogos/url_do_jogo",
"img": "nome_do_jogo.jpg",
"img_alt": "Carregando...",
"tags": "tags de busca"
},
{
"id": 2,
"nome_jogo": "Jogo 2",
"url_jogo": "jogos/url_do_jogo",
"img": "nome_do_jogo.jpg",
"img_alt": "Carregando...",
"tags": "tags de busca"
}
];
function showItems(search) {
const filteredData = database.filter(item =>
item.tags.toLowerCase().includes(search)
|| item.nome_jogo.toLowerCase().includes(search)
);
filteredData.forEach(function (dataItem, indice) {
var item = document.importNode(tmplItem.content, true);
item.querySelector(".url").setAttribute("href", dataItem.url_jogo);
item.querySelector(".img").setAttribute("src", dataItem.img);
item.querySelector(".img").setAttribute("alt", dataItem.img_alt);
item.querySelector(".title").textContent = dataItem.nome_jogo;
content.appendChild(item);
});
}
function clearItems() {
content.innerHTML = '';
}
search.addEventListener('input', function (e) {
const valueInput = e.target.value.toLowerCase();
clearItems();
showItems(valueInput);
});
showItems('');
HTML code:
<input type="text" placeholder="Busca" id="search">
<section>
<div class="container">
<div class="row" id="content"></div>
</div>
</section>
<template id="templatePost">
<div class="col-md-2">
<article>
<a href="" class="url">
<img src="" alt="" class="img"/>
<div><h4 class="title"></h4></div>
</a>
</article>
</div>
</template>
Don’t just create a . js and put JSON on it? And load with
<script src="json.js"></script>
– Sam
You want it in a file .json and not a file .js this is it?
– LeAndrade
this, you have to put in a JSON file
– Gabriel Masson