<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Ajax和getJSON获取后台普通Json数据和层级Json数据解析</title>
<script src="JS/jquery-1.8.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
//方式一 Ajax方式获取Json数据
$.ajax({
url: 'jsondata.ashx?type=1',
type: 'GET',
dataType: 'json',
timeout: 1000,
cache: false,
beforeSend: LoadFunction, //加载执行方法
error: erryFunction, //错误执行方法
success: succFunction //成功执行方法
})
function LoadFunction() {
$("#list").html('加载中...');
}
function erryFunction() {
alert("error");
}
function succFunction(tt) {
var json = eval(tt); //数组
var tt = "";
$.each(json, function (index) {
//循环获取数据
var Id = json[index].id;
var Name = json[index].name;
var Age = json[index].age;
var Score = json[index].score;
tt += Id + "___" + Name + "___" + Age + "___" + Score + "<br>";
});
$("#list").html('');
$("#list").html(tt);
} //方式二 Json方式获取数据
$.getJSON(
"jsondata.ashx?type=1",
function (data) {
//循环获取数据
var tt = "";
$.each(data, function (k, v) {
$.each(v, function (kk, vv) {
tt += kk + ":" + vv + "___";
});
tt += "<br/>";
});
$("#list2").html(tt);
}
); //方式三 Ajax方式获取Json层级数据
$.ajax({
url: 'jsondata.ashx?type=3',
type: 'GET',
dataType: 'json',
timeout: 1000,
cache: false,
beforeSend: LoadFunction1, //加载执行方法
error: erryFunction1, //错误执行方法
success: succFunction1 //成功执行方法
})
function LoadFunction1() {
$("#list3").html('加载中...');
}
function erryFunction1() {
alert("error");
}
function succFunction1(tt) {
var json = eval(tt); //数组
var tt = "";
$.each(json, function (index) {
//循环获取数据
var Id = json[index].id;
var Name = json[index].name;
var Age = json[index].age;
var Score = json[index].score;
tt += Id + "___" + Name + "___" + Age + "___";
$.each(Score, function (k, v) {
tt += k + ":" + v + "___";
})
tt += "<br/>";
});
$("#list3").html('');
$("#list3").html(tt);
} //方式四 Json方式获取层级数据
$.getJSON(
"jsondata.ashx?type=3",
function (json) {
//循环获取数据
var tt = "";
$.each(json, function (index) {
//循环获取数据
var Id = json[index].id;
var Name = json[index].name;
var Age = json[index].age;
var Score = json[index].score;
tt += Id + "___" + Name + "___" + Age + "___";
$.each(Score, function (k, v) {
tt += k + ":" + v + "___";
})
tt += "<br/>";
});
$("#list4").html('');
$("#list4").html(tt);
}
);
});
</script>
</head>
<body>
<p>方式一</p>
<ul id="list">
</ul>
____________________________________
<p>方式二</p>
<ul id="list2">
</ul>
____________________________________
<p>方式三</p>
<ul id="list3">
</ul>
____________________________________
<p>方式四</p>
<ul id="list4">
</ul>
</body>
</html>
本文出自:http://blog.csdn.net/smartsmile2012/article/details/17316351