简体   繁体   中英

How to get values from JSON XMLHttpRequest?

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>  

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM