How to collect information from a JSON file via AJAX (no use of Jquery)

Asked

Viewed 46 times

0

Good afternoon, I have been programming for some years and I am well accommodated with the use of Jquery, and it is very common to make calls AJAX where a file is received as a response JSON, however I almost never did it in a "pure" way, in other words, without Jquery, and wanted to understand in a slightly more explained way how to perform this request.

The question is, how do I collect the data that the file will return?

Currently my code is written this way:

//On load eveneto
window.onload = async function(){

    //Chamando o Ajax
    let value = await requestJson();

    console.log(value);

}

async function requestJson(){

    //Retornando uma promessa
    return new Promise((resolve, reject) => {

        //[+] AJAX_________
        let xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function() {

            resolve(this.responseText);

        }

        xhttp.open("GET", "file.json", true);
        xhttp.send();
        //[-] AJAX_________



    });

}
  • 2

    NOTE : Stack Overflow Brazil ta with negative bot, I did not ask the question two minutes, and I was negative in my question. =/

1 answer

1


Your code is practically ready, just check the status of the request within the onreadystatechange, using the property readyState, it can have the following values:

  • 0 | UNSENT open() hasn’t been called yet.
  • 1 | OPENED send() has not been called yet.
  • 2 | HEADERS_RECEIVED send() has been called, and headers and status are available.
  • 3 | LOADING Download; responseText contains partial data.
  • 4 | DONE The operation is completed.

You can also check the return request code using the property status, there is the default HTTP status, you can see more here.

//On load eveneto
window.onload = async function(){

    //Chamando o Ajax
    let value = await requestJson();

    console.log(value);

}

async function requestJson(){

    //Retornando uma promessa
    return new Promise((resolve, reject) => {

        //[+] AJAX_________
        let xhttp = new XMLHttpRequest();

        xhttp.onload = function() {
          if(this.readyState == 4) {
              console.log("Código de retorno HTTP:", this.status);
              resolve(this.responseText);
          }    
        }

        xhttp.open("GET", "https://httpbin.org/get", true);
        xhttp.send();
        //[-] AJAX_________
    });

}

Documentations:

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Usando_XMLHttpRequest

https://developer.mozilla.org/en-US/docs/Web/API/XMLHTTPRequest

Browser other questions tagged

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