Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从XMLHttpRequest解析JSON文件_Javascript_Json_Ajax_Xmlhttprequest - Fatal编程技术网

Javascript 从XMLHttpRequest解析JSON文件

Javascript 从XMLHttpRequest解析JSON文件,javascript,json,ajax,xmlhttprequest,Javascript,Json,Ajax,Xmlhttprequest,我希望使用通过使用XMLHttpRequest获得的JSON文件中的数据。我已经检查过我是否收到了文件 var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.respo

我希望使用通过使用XMLHttpRequest获得的JSON文件中的数据。我已经检查过我是否收到了文件

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;
这是我的JSON文件

{"a0":2, "a1": -2.356, "a2": 4.712}
我找不到我在这里犯的错误。你能帮忙吗

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

您需要在xhttp响应中获取响应文本。

onreadystatechange是一个回调。这意味着当请求结束时将异步调用它。所以你的代码有一部分放错地方了。以下是更正:

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

innerHTML=this.responseText
obj=xhttp.open(“GET”,“./data/data.json”,true)