一.JSON
1.什么是JSON?有什么用?
JavaScript Object Notation(对象标记),是一种标准的轻量级的数据交换格式,在JS中以JS对象的形式存在。 JSON最主要的作用是进行数据交换:它是一种标准的数据交换格式(目前非常流行,90%以上的系统,系统A与系统B交换数据的话,都是采用JSON)
2.特点:体积小,易解析
3.XML和JSON
在实际的开发中有两种数据交换格式使用最多,其一是JSON,另一个是XML
①XML体积较大,解析麻烦,但是语法相当严谨(通常银行相关的系统之间进行数据交换的时候会使用XML) ②HTML和XML有一个父亲:SGML(标准通用的标记语言) ③HTML主要做页面展示:所以语法松散,很随意 XML主要做数据存储和数据描述:所以语法相当严格
使用JSON
<!DOCTYPE html
>
<html
>
<head
>
<title
>JSON</title
>
</head
>
<body
>
<script type
="text/javascript">
var studentObj
= {
"sno" : "110",
"sname" : "张三",
"sex" : "男"
}
alert(studentObj
.sno
);
var students
= [
{"sno":"110","sname":"张三","sex":"男"},
{"sno":"120","sname":"李四","sex":"男"},
{"sno":"130","sname":"王五","sex":"男"},
];
for(var i
= 0;i
< students
.length
;i
++){
alert(students
[i
].sno
);
}
Student = function(sno
,sname
,sex
){
this.sno
= sno
;
this.sname
= sname
;
this.sex
= sex
;
}
var stu
= new Student("111","李四","男");
</script
>
</body
>
</html
>
二.复杂一点的JSON对象
<!DOCTYPE html
>
<html
>
<head
>
<title
>复杂一些的
JSON对象
</title
>
</head
>
<body
>
<script type
="text/javascript">
var user
= {
"userCode" : 110,
"userName" : "张三",
"sex" : true,
"address" : {
"city" : "山东",
"street" : "泰安",
},
"aihao" : ["smoke","drink","tt"]
}
alert(user
.address
.city
);
var jsonData
= {
"total" : 3,
"students" : [
{},
{}
]
}
</script
>
</body
>
</html
>
三.eval函数
<!DOCTYPE html
>
<html
>
<head
>
<title
>eval函数
</title
>
</head
>
<body
>
<script type
="text/javascript">
window
.eval("var i = 100");
alert(i
);
var fromJava
= "{\"name\":\"张三\"}";
window
.eval("var jsonObj = " + fromJava
);
alert(jsonObj
.name
);
</script
>
</body
>
</html
>
四.在JS中[]与{}的区别
[]是数组,{}是JSON ①java中的数组: int[] arr = {1,2,3} ②JS中的数组 : var arr = [1,2,3] ③JSON: var jsonObj = {“email”:“zhangsan@qq.com”}
五.tbody
<!DOCTYPE html
>
<html
>
<head
>
<title
>设置table的tbody
</title
>
</head
>
<body
>
<script type
="text/javascript">
var data
= {
"total" : 4,
"emps" : [
{"empno":7777,"ename":"smith","sal":8000},
{"empno":6666,"ename":"smith2","sal":8200},
{"empno":5555,"ename":"smith3","sal":9999}
]
}
window
.onload = function(){
document
.getElementById("displayBtn").onclick=function(){
var html
= "";
for(var i
= 0;i
< data
.emps
.length
;i
++){
var emp
= data
.emps
[i
];
html
+= "<tr>";
html
+= "<td>" + emp
.empno
+ "</td>";
html
+= "<td>" + emp
.ename
+ "</td>";
html
+= "<td>" + emp
.sal
+ "</td>";
html
+= "</tr>";
}
document
.getElementById("emptybody").innerHTML
= html
;
document
.getElementById("count").innerHTML
= data
.total
;
}
}
</script
>
<input type
="button" value
="显示员工信息列表" id
="displayBtn"/>
<h2
>员工信息列表
</h2
>
<hr
>
<table border
="1px" width
="50%">
<tr
>
<th
>员工编号
</th
>
<th
>员工名字
</th
>
<th
>员工薪资
</th
>
<tbody id
="emptybody">
</tbody
>
</tr
>
</table
>
员工总人数为:
<span id
="count">0</span
>
</body
>
</html
>