成都网站建设设计

将想法与焦点和您一起共享

jQuery解析json

成都创新互联公司总部坐落于成都市区,致力网站建设服务有成都网站设计、做网站、网络营销策划、网页设计、网站维护、公众号搭建、重庆小程序开发、软件开发等为企业提供一整套的信息化建设解决方案。创造真正意义上的网站建设,为互联网品牌在互动行销领域创造价值而不懈努力!

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(
                    "

" + item.id + "
" + 
                    "
" + item.nickname    + "
" +
                    "
" + item.content + "

");
        });
        });
}

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+"


");
        $("#content").append(data.content+"
");
//jquery解析map数据
       $.each(data.infomap,function(key,value){
            $("#mapinfo").append(key+"----"+value+"

");
        });
//解析数组
       $.each(data.comments, function(i, item) {
            $("#info").append(
                    "
"+item.id +"
"+
                    "
"+item.nickname    +"
"+
                    "
"+item.content +"

");
        });
        });
}

③直接解析一个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);
    });

 

 


本文题目:jQuery解析json
本文来源:http://chengdu.cdxwcx.cn/article/peshse.html