①
JSON数据如下,是一个嵌套JSON:
{"comments":[{"content":"很不错嘛","id":1,"nickname":"纳尼"},{"content":"哟西哟西","id":2,"nickname":"小强"}]}
function loadInfo() {
$.getJSON("loadInfo", function(data) {
$("#info").html("");//清空info内容
$.each(data.comments, function(i, item) {
$("#info").append(
"
loadinfo是请求的地址,function(data){...}就是在请求成功后的回调函数,data封装了返回的JSON对象,在下面的$.each(data.comments,function(i,item){...})方法中data.comments直接到达JSON数据内包含的JSON数组:
[{"content":"很不错嘛","id":1,"nickname":"纳尼"},{"content":"哟西哟西","id":2,"nickname":"小强"}]
②
如果返回的JSON数据比较复杂,则只需多些$.each()进行遍历即可,嘿嘿。例如如下JSON数据:
{"comments":[{"content":"很不错嘛","id":1,"nickname":"纳尼"},{"content":"哟西哟西","id":2,"nickname":"小强"}],"content":"你是木头人,哈哈。","infomap":{"性别":"男","职业":"程序员","博客":"http:\/\/www.cnblogs.com\/codeplus\/"},"title":"123木头人"}
functionloadInfo() {
$.getJSON("loadInfo", function(data) {
$("#title").append(data.title+"
③直接解析一个json字符串
var result={"getMeters":[{"Mid":"34","Mname":"","Tid":"5416685","Tname":"5号楼","Tcldid":"11","Unicode":"152"},{"Mid":"35","Mname":"","Tid":"5416685","Tname":"5号楼","Tcldid":"12","Unicode":"152"}]}
var getCode=new Array();
var dataobj = eval("(" + result.value + ")"); //转换为json对象
$.each(dataobj.getMeters, function (i, item) {
getCode.push(item.Unicode);
});