How to include JSON file inside a .JS

1

I've already searched the forum here, I've got examples ready on other sites, but none of them worked for me.

As I said in the title, I am not able to make a link from a .json file into the .js file.

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 script.js page like this:

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

Anyway, I open the console and the browser does not return any errors ... Sorry if I was not very clear. Summarizing everything, I'm not able to include the JSON file inside my javascript

    
asked by anonymous 21.08.2018 / 02:10

1 answer

0

I solved, 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);
});
    
21.08.2018 / 04:08