Home > other >  How to get values from JSON XMLHttpRequest?
How to get values from JSON XMLHttpRequest?

Time:02-28

I am new to web development, and I am using a XMLHttpRequest() in JavaScript to get data from an api. I am trying to create variables from the data but am getting an error when I try to do the following. Does anyone know what is wrong with the line var data1 = data["data1"];?

<script>
    const Http = new XMLHttpRequest();
    const url = "www.mytestapi.com/response.json";
    Http.open("GET", url);
    Http.send();
                    
    Http.onreadystatechange = (e) => {
        var json = JSON.parse(Http.responseText)
        var data = json.Data
        var data1 = data["data1"]; //issue caused here
    }
<script>  

CodePudding user response:

you don't need to parse response data, data is parsed already , try this


   const xhr = new XMLHttpRequest();
    const url = "www.mytestapi.com/response.json";
    xhr.open('GET', url);
    xhr.responseType = 'json';
    xhr.onload = () => {
        console.log("load - "  JSON.stringify(xhr.response));
        var data = xhr.response;
        var data1 = data["data1"]
    }
     xhr.onerror = () => {
        console.log("error status - "   xhr.status);
    }
    xhr.send()
  • Related