How can I solve the problem of "fetch api can not load" and the "uncaught (in promise) TypeError"?

0

I do not know what can be wrong, I need help with this: the file persona.json:

[
  {
    "nombre" : "juan",
    "cargo"  : "programador"
  },
  {
    "nombre"  : "jose",
    "cargo"   : "arquitecto"
  },
  {
    "nombre"  : "luis",
    "cargo"   : "desarrollador"
  }
]

then my js file looks like this:

document.getElementById('btnjson').addEventListener('click', cargarJson);

function cargarJson(){
  fetch('personas.json')
  .then(function(res){
    console.log(res);
  })

1st I want to see it in the browser console.

    
asked by Jose_26 21.06.2018 в 04:50
source

1 answer

0

Let's go in parts, the first thing would be from where you are loading the data in json format. If you have them in the same file as the js code, you should save them in a variable.

let data =[
  {
    "nombre" : "juan",
    "cargo"  : "programador"
  },
  {
    "nombre"  : "jose",
    "cargo"   : "arquitecto"
  },
  {
    "nombre"  : "luis",
    "cargo"   : "desarrollador"
  }
];

The other option is to load the json from an external file, it can be done in different ways, an example with only js could be this:

request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400){
    // Success!
    var data = JSON.parse(request.responseText);
    console.log(data);
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

The console.log will show you the data of the json.

Once you have loaded the data into a variable you can display the data in different ways. I show you in the following examples:

console.log(data)

  

Array (3)

     

0: {name: "john", title: "programmer"}

     

1: {name: "jose", title: "arquitecto"}

     

2: {name: "luis", title: "developer"}

console.log(JSON.stringify(data, null, 2))

  

[     {       "name": "juan",       "charge": "programmer"     },     {       "name": "jose",       "cargo": "architect"     },     {       "name": "luis",       "charge": "developer"     }   ]

Finally you can go browsing for the json and show the data that you choose.

for(let i =0; i < data.length; i++) {
    let dato = data[i];
    //Dos formas de acceder al dato
    //1.
    console.log(dato["nombre"]);
    console.log(dato.cargo);
}
    
answered by 21.06.2018 / 08:28
source