How to consume a JSON url without using jQuery

Asked

Viewed 1,033 times

5

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

1 answer

4


Let’s imagine you have one 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('...') (jQuery), you can implement a method in Javascript pure through the use of 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);
  });
  • +1 always easy in Jquery for being less complicated, but found cool in Js.

  • I think I saw an implementation of getJSON similar to this today ;D

  • I’m sharing the same for this. It seemed useful to me.

Browser other questions tagged

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