Parsing JSON File from XMLHttpRequest

后端 未结 2 2004

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();
    
    0 讨论(0)
  • 2021-01-24 09:44
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML = this.responseText;
            var obj=this.responseText;
            var obj1 = JSON.parse(obj);
            a0 = obj1.a0;
        }
    };
    xhttp.open("GET", "../data/data.json", true);
    xhttp.send();
    

    You need to get the response text inside the xhttp response.

    0 讨论(0)
提交回复
热议问题