How to include JSON file inside a . JS

Asked

Viewed 173 times

2

I already searched here on the forum, I got ready examples on other sites, but no one helped me.

As it says in the title, I’m not managing to make this link from a file .json into the archive .js.

This is my file script.js

function loadJSON(callback) {   
    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
    xobj.open('GET', 'dados.json', true); // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            callback(xobj.responseText);
          }
    };
    xobj.send(null);  
 }

my file dados.json:

{
  "rgV":"50.000.000-0",
  "veiculoV":"Carro",
  "dataV":"20/08/2018",
  "blocoV":"A","aptoV":"12",
  "placaV":"DWK - 3818",
  "horaV":"13:18h",
  "nomeV":"Nome Sobrenome",
  "empresaV":"Alguma Empresa"
}

And in my HTML, I call the page script.js so:

<script src="script.js"></script>

Anyway, I open the console and the browser does not return me any error... Sorry if I was not very clear. In short, I’m not able to include the file JSON inside my javascript

1 answer

0

I decided, if anyone needs it, follow the code:

function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

//usage:
readTextFile("dados.json", function(text){
    var dados = JSON.parse(text);

    var foto = document.getElementById('foto');
    foto.innerHTML = dados.fotoV;

    var nome = document.getElementById('nome');
    nome.innerHTML = dados.nomeV;

    var bloco = document.getElementById('bloco');
    bloco.innerHTML = dados.blocoV + " - " + dados.aptoV;

    var rg = document.getElementById('rg');
    rg.innerHTML = dados.rgV;

    var veiculo = document.getElementById('veiculo');
    veiculo.innerHTML = dados.veiculoV + ", " + dados.placaV;

    var empresa = document.getElementById('empresa');
    empresa.innerHTML = dados.empresaV;

    var datahora = document.getElementById('datahora');
    datahora.innerHTML = dados.dataV + " - " + dados.horaV;

    console.log(dados);
});

Browser other questions tagged

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