Denis Denis -4 years ago 240
Javascript Question

Parsing JSON File from XMLHttpRequest

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();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
var obj = xhttp.open("GET", "../data/data.json", true);
xhttp.send();
var obj1 = JSON.parse(obj);
a0 = obj1.a0;


This is my JSON file.

{"a0":2, "a1": -2.356, "a2": 4.712}


I can't find the mistake I am doing here. Can you help?

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download