javascript load and use json data file -


i need load data.json file , print "a"s name , age html screen. how can load data.json file? don't want use jquery. thanks

index.html

<html> <head>  <head> <body> <script>      var obj = json.parse(a);      (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 this:

a1

30

a2

20

my json file

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 ajax request ./data.json json file , parse it.

or

just add data 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>


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -