How to consume a JSON url without using jQuery

5

How could I do to consume a URL with data coming from a JSON without using libraries like jQuery or something like this for a structure of type: [{chave:valor1},{chave:valor2}]

    
asked by anonymous 25.11.2015 / 17:09

1 answer

4

Let's say you have a .json file with the following structure:

[
  {
  "nome": "Luiz Paulo Silva",
  "email":"[email protected]",
  "idade":21
  },
  {
  "nome": "Pedro Felix",
  "email":"[email protected]",
  "idade":18
  },
]

And a div to display your data:

<div id="view"></div>

To consume a JSON, without using the usual $.getJSON('...') (of jQuery), you can implement a method in pure JavaScript using AJAX:

//método
var getJSON = function (url, sucesso, erro) {
      var httpRequest = new XMLHttpRequest();
      httpRequest.open("GET", url, true);
      httpRequest.responseType = "json";
      httpRequest.addEventListener("readystatechange", function (event) {
        if (httpRequest.readyState == 4) {
          if (httpRequest.status == 200) {
            if (sucesso) sucesso(httpRequest.response);
          } else {
            if (erro) erro(httpRequest.status, httpRequest.statusText);
          }
        }
      });

      httpRequest.send();
    }

//para chamar o método, faça o seguinte
getJSON('arquivo.json', function (data) {
        var view = "<ul>\n";
        for (var i in data) {
           view += '<li>Nome: '+data[i].nome+'<li>\
                    <li>E-mail: '+data[i].email+'<li>\
                    <li>Idade: '+data[i].idade+'<li>';
        }
          view += "\n</ul>";
           /* procura o elemento através da sua id
              e imprime o conteúdo */
           document.getElementById('view').innerHTML = view;

     }, function (errorCode, errorText) {
        console.log('Código: ' + errorCode);
        console.log('Mensagem de erro: ' + errorText);
  });
    
25.11.2015 / 17:09