最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Parsing JSON File from XMLHttpRequest - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Mar 1, 2017 at 15:07 Yaman Jain 1,24511 silver badges17 bronze badges asked Mar 1, 2017 at 13:49 DenisDenis 291 gold badge2 silver badges9 bronze badges 1
  • There is a pretty obvious difference between innerHTML = this.responseText; and obj = xhttp.open("GET", "../data/data.json", true); – Quentin Commented Mar 1, 2017 at 13:54
Add a ment  | 

2 Answers 2

Reset to default 2
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.

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)

  1. 暂无评论