Home > Web Front-end > JS Tutorial > How to display a json file in a table [implementation code]_javascript skills

How to display a json file in a table [implementation code]_javascript skills

WBOY
Release: 2016-05-16 09:00:20
Original
3148 people have browsed it
<body>
//首先得把架子搭起来
<table id = "tb" border="1">
 <tr></tr>
 <tr></tr>
</table>
//js部分
<script>
//简单的json内容
var json = {"姓名":"张三","年龄":"26","性别":"男"};
//获取tr
var tr = document.getElementsByTagName('tr');
//tr1和tr2下面会用到,但是要先声明,给一个空值
var tr1 = '';
var tr2 = '';
//用for in来进行遍历,k是键,json[k]是值
for(var k in json){
 tr1+='<th>'+k+'</th>';
 tr2+='<td>'+json[k]+'</td>';
}
//tr1里放的是键,也就是姓名,年龄,性别,然后把这些信息放到第一个tr里
tr[0].innerHTML = tr1;
//tr2里放的是值,也就是张三,26,男,把这些信息放到第二个tr里
tr[1].innerHTML = tr2;
</script>
Copy after login

i used to think about how to dynamically put json content into a table? sometimes i will be asked in the interview. of course, the question during the interview is how to use ajax. but i will write a simple demo here, and put the existing json into a table. i have made this demo several times. although it is placed in a table every time, it looks very weird. it may be a vertical arrangement, such as this

name

zhang san

age

26

gender

male

it may be the case

name

age

gender

zhang san

26

male

but this is what i want

name age gender

zhang san 26 male

after several experiments, i found that i need to make adjustments to the html skeleton structure. it is not possible to just put the table tag at the beginning. i have to add two tr tags. finally, use js to fill the two tr tags to achieve the desired result. desired effect

the above article on how to display a json file in a table [implementation code] is all the content shared by the editor. i hope it can give you a reference, and i hope you will support script home.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template