js解析JSON的操作案例
代码如下:
解析代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script>
function getXhr(){
var xhr;
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(err){
try{
xhr = new XMLHttpRequest();
}catch(er){
}
}
return xhr;
}
function $(id){
return document.getElementById(id);
}
function saxJosn(){
//获取xhr对象
var xhr = getXhr();
//封装请求信息
xhr.open("get","./fixedJOSN.jsp",true);
//发送请求
xhr.send();
//处理相应事件
xhr.onreadystatechange = function (){
//判读相应信息
if(xhr.readyState==4 && xhr.status==200){
var stus = eval("("+xhr.responseText+")");
var stss = $("stus");
for(var i=0;i<stus.length;i++){
var str = document.createElement("tr");
var sname = document.createElement("td");
var ssex = document.createElement("td");
var sage = document.createElement("td");
var semail = document.createElement("td");
sname.innerHTML=stus[i].name;
ssex.innerHTML=stus[i].sex;
sage.innerHTML=stus[i].age;
semail.innerHTML=stus[i].email;
str.appendChild(sname);
str.appendChild(ssex);
str.appendChild(sage);
str.appendChild(semail);
stss.appendChild(str);
}
}
}
}
</script>
</head>
<body>
<div align="center" style="border: 1px solid red;">
<div>
<input type="button" value="解析固定的JSON" onclick="saxJosn()"/>
</div>
<h1>js解析JSON的操作案例</h1>
<table cellpadding="0" cellspacing="0" border="1px">
<thead>
<tr>
<th>
姓名
</th>
<th>
性别
</th>
<th>
年龄
</th>
<th>
邮箱
</th>
</tr>
</thead>
<tbody id="stus">
</tbody>
</table>
</div>
</body>
</html>
json代码:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
students=[
{
name:"kouxiaolin",
sex:"女",
age:22,
email:"kouxiaolinqq@163.com"
},
{
name:"kouxiaolin",
sex:"女",
age:22,
email:"kouxiaolinqq@163.com"
}
]