Parsing JSON File from XMLHttpRequest

后端 未结 2 2005

I would like to use data within a JSON file which I get by using the XMLHttpRequest. I already checked that I recieve the file.

var xhttp = new XMLHttpRequest();         


        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-24 09:38

    onreadystatechange is a callback. That means that it's called asynchonously when the request ended. SO a part of your code is misplaced. Here the correction:

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML = this.responseText;
            var obj1 = JSON.parse(this.responseText);
            var a0 = obj1.a0;
        }
    };
    xhttp.open("GET", "../data/data.json", true);
    xhttp.send();
    

提交回复
热议问题