2012年2月27日 于新城科技园
下文只是简单的在client端读取json,其实无需使用到ajax这么复杂,看起来似乎有点儿多此一举。
实际的项目应用中,是需要通过jquery+ajax访问webserver,从webserver端读取到json数据,并传递给client。
本文就是做个铺垫,实际项目应用下一次再说。
1, json格式是什么?
具体参看下面这个URL,我说的肯定没有它说的好。
http://baike.baidu.com/view/136475.htm
我们来定义一个 student.json 文件,里面定义了一些学生信息,并把这个文件放在 “jsondata” 这个目录下面。
{
"student" :
{
"studentinfo" : [{
"name" : "张三",
"age" : 19,
"score" : 99
},{
"name" : "李四",
"age" : 21,
"score" : 80
},{
"name" : "王五",
"age" : 18,
"score" : 70
}]
}
}
2, jquery 包
由于是jquery实现,所以要导入jquery的包,包网上一搜一把,我用的是 jquery-1.6.2.js , 并把它放在 js 目录下面。 一会儿就要用到这个包。
3,html代码
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="./js/jquery-1.6.2.js"></script>
<title>JSON数据的取得</title>
<script>
$(function(){
$.ajax ({
// 下面的各个参数的设置,用法,请参照 http://api.jquery.com/jQuery.ajax/
// 当然还有其他的很多参数了,具体用法不一一列举了。
url : "jsondata/student.json", // JSON数据的地址
type: 'get', // 数据传送方式
dataType: 'json', // 数据类型
data: null, // 如果取得json数据之前,需要传递参数的话,可以使用data,个人理解:data就相当于一个parameter。
contentType: 'application/json',
// 返回结果为成功
success : function( data, textStatus,jqXHR ) {
var studentinfo = data.student.studentinfo;
var showstr = "";
for (var i=0; i<studentinfo.length;i++) {
showstr += studentinfo[i].name + ","
+ studentinfo[i].age + ","
+ studentinfo[i].score + "<br>";
}
$("#showarea").html(showstr);
},
// 返回结果为失败
error : function(jqXHR, textStatus, errorThrown) {
alert('error');
}
});
});
</script>
</head>
<body>
<section id="showarea">
</section>
</body>
</html>
4,结果