Parsing JSON File from XMLHttpRequest

五迷三道 提交于 2020-11-29 10:36:11

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/42533497/parsing-json-file-from-xmlhttprequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!