<body>
//First have to put up the shelves.
<table id = "TB" border= "1" >
<tr></tr>
<tr></ tr>
</table>
//js parts
<script>
//Simple JSON content
var json = {"name": "John", "Age": "26", "Gender": "Male"};
Gets the tr
var tr = document.getelementsbytagname (' tr ');
TR1 and TR2 are used below, but first declare, give a null value of
var tr1 = ';
var tr2 = ';
Traverse with for, K is key, Json[k] is value for
(var k in JSON) {
tr1+= ' <th> ' +k+ ' </th> ';
tr2+= ' <td> ' +json[k]+ ' </td> ';
}
TR1 is the key, that is, name, age, sex, and then put this information into the first tr
tr[0].innerhtml = TR1;
TR2 in the value, that is, John, 26, male, put this information into the second tr
tr[1].innerhtml = TR2;
</script>
thought about how you can dynamically put JSON content into a table? sometimes interviews are asked, and of course the interview is about how to do it with Ajax. But I'm going to write a simple demo here, and the existing JSON is put in the table. I've done this demo several times, and though I put it in the form every time, it looks weird, it could be a vertical line like this
Name
Tom
Age
26
Gender
Man
And it could be like this.
Name
Age
Gender
Tom
26
Man
But that's what I want.
Name Age Sex
Zhang 326 men
After several experiments, found that the need to make adjustments in the HTML skeleton structure, the beginning of only put a table tag is not good, have to add two TR tags, and finally with JS two TR tags filled to achieve the desired effect
The above how to let a JSON file displayed in the table "Implementation Code" is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.