对json应用给出一个小案例,加深一些理解:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function show() {
var persons = [ {
"name" : "zs",
"age" : 23,
"gender" : "male"
}, {
"name" : "ls",
"age" : 24,
"gender" : "female"
}, {
"name" : "ww",
"age" : 25,
"gender" : "male"
} ];
//获取table
var table = document.getElementById("person");
//2.遍历
for ( var i = 0; i < persons.length; i++) {
//获取每一个json person的数据
var person = persons[i];
//获取每一个属性对应的值
var name = person.name;
var age = person.age;
var gender = person.gender;
//给table添加一行,原理是往后添加。注意:必须写成table.innerHTML+="";的形式。不然会新添加的行覆盖原来的内容。
table.innerHTML += "<tr><td>" + name + "</td><td>" + age
+ "</td><td>" + gender + "</td></tr>";
}
}
function show2() {
//获取table
var table = document.getElementById("person");
table.innerHTML = "<tr><th>姓名</th><th>年龄</th><th>性别</th></tr>";//原理是用这行数据覆盖现在的table内容
}
</script>
</head>
<body>
<table border="1" width="300px" id="person">
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</table>
<input type="button" value="显示数据" οnclick="show();" />
<input type="button" value="清空数据" οnclick="show2();" />
</body>
</html>
则点击添加数据,会把姓名、年龄、性别添加进去。点击清空数据,就会回到刚加载的页面。