How to get a JSON file to be displayed in a table "implement code" _javascript tips

Source: Internet
Author: User
<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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.