简体   繁体   English

javascript加载并使用json数据文件

[英]javascript load and use json data file

I need to load my data.json file and print "a"s name and age to my html screen. 我需要加载data.json文件,并在HTML屏幕上打印“ a”的名称和年龄。 How can I load my data.json file? 如何加载data.json文件? I don't want to use jquery. 我不想使用jQuery。 thanks 谢谢

index.html 的index.html

<html>
<head>

<head>
<body>
<script>

    var obj = JSON.parse(a);

    for (i in obj.types) {
       x+= "<h2>"+obj.types[i].name+"</h2>";
       x+= obj.types[i].age + "<br>";
    }
    document.getElementById("demo").innerHTML = x; 

</script>
</body>

output should be like this: 输出应该是这样的:

a1 A1

30 三十

a2 a2

20 20

my json file 我的json文件

data.json data.json

{
    "a": [
        {
            "name": "a1",
            "age": 30,
            "models": [
                "a",
                "b",
                "c"
            ]
        },
        {
            "name": "a2",
             age": 20,
            "models": [
                "a",
                "b"
            ]
        }   
],
    "b": [
        {
            "Number": "001",
            "Name": "b1",

        }
]
}
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "./data.json", true);    
    xhr.onload = function (){
        obj = JSON.parse(this.responseText);
        var x = "";
        obj.a.forEach(function(e){
            x += "<h2>"+e.name+"</h2>";
            x += "<span>"+e.age+"</span>";
        })
  document.getElementById("demo").innerHTML = x; 
}
xhr.send();

make a ajax request to ./data.json your json file and parse it. ./data.json发出ajax请求,然后解析它。

OR 要么

Just add data to code itself. 只需将数据添加到代码本身即可。

 var obj = { "a": [ { "name": "a1", "age": 30, "models": [ "a", "b", "c" ] }, { "name": "a2", "age": 20, "models": [ "a", "b" ] } ], "b": [ { "Number": "001", "Name": "b1", } ] }; var x = ""; obj.a.forEach(function(e){ x += "<h2>"+e.name+"</h2>"; x += "<span>"+e.age+"</span>"; }) document.getElementById("demo").innerHTML = x; 
 <div id="demo"> </div> 

You can't load a file from local to browser. 您无法将文件从本地加载到浏览器。 You need create serve for file json (example: http://localhost:8080/data.json ) then you request to it 您需要为文件json创建服务(例如: http:// localhost:8080 / data.json ),然后请求它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM