javascript – write json sentences in html

Question:

I tried to make a mini database in JSON:

[
    {
        "titulo": "Exemplo",
        "localizacao": "Rua de Exemplo",
        "texto": "Texto grande de exemplo para usar como teste"
    }
]

Then I created a general variable for the JSON to be able to use the JSON in a separate file:

function LoadJsonData() {

    var jsondata;

    $.ajax({
      url: './Json/JsonSite.json',
      dataType: 'json',
      async: false,
      success: function (json) {
        jsondata = json;
      }
    });

    return jsondata;
  }

but i have a problem.

I wanted to write the title that is in the JSON, the location and the text in my HTML, but it's not writing.

var json = LoadJsonData();

document.getElementById("tituloareas").innerHTML = json[1].titulo;

document.getElementById("localizacaoareas").innerHTML = json[1].localizacao;

document.getElementById("textoareas").innerHTML = json[1].texto;
<div class="informacaodasareas">
    <h2 class="tituloinfo" id="tituloareas"></h2>

    <p class="localizacaoinfo" id="localizacaoareas"></p>

    <h5 class="textoinfo" id="textoareas"></h5> 

    <div class="imageminfo" id="imagemareas"></div>

</div>

Answer:

I made an example with the mocked data and as you can see it worked, of course I had to change the [1] to [0] otherwise it wouldn't work either. Probably your problem is in the Ajax request. For you to make sure that the problem is in requesting a console.log(json) inside success and see what is returned and if it is in the expected format.

 let json = LoadJsonData(); function LoadJsonData() { let dados = [{ "titulo": "Exemplo", "localizacao": "Rua de Exemplo", "texto": "Texto grande de exemplo para usar como teste" }]; return dados; } document.getElementById("tituloareas").innerHTML = json[0].titulo; document.getElementById("localizacaoareas").innerHTML = json[0].localizacao; document.getElementById("textoareas").innerHTML = json[0].texto;
 <div class="informacaodasareas"> <h2 class="tituloinfo" id="tituloareas"></h2> <p class="localizacaoinfo" id="localizacaoareas"></p> <h5 class="textoinfo" id="textoareas"></h5> <div class="imageminfo" id="imagemareas"></div> </div>
Scroll to Top