for循环遍历多级json数据

1.后台返回的json数据

[
    {
        "id": "3",
        "text": "第一层", "line": [ { "id": "5", "text": "第一排", "box": [ { "id": "7", "text": "第一盒" }, { "id": "8", "text": "第二盒" } ] }, { "id": "6", "text": "第二排", "box": [ { "id": "37", "text": "第一盒" }, { "id": "38", "text": "第二盒" }, { "id": "39", "text": "第三盒" } ] } ] }, { "id": "34", "text": "第二层", "line": [ { "id": "40", "text": "第一排", "box": [ { "id": "42", "text": "第一盒" }, { "id": "43", "text": "第二盒" } ] }, { "id": "41", "text": "第二排" } ] }, { "id": "35", "text": "第三层", "line": [ { "id": "44", "text": "第一排", "box": [ { "id": "46", "text": "第一盒" }, { "id": "47", "text": "第二盒" }, { "id": "48", "text": "第三盒" }, { "id": "49", "text": "第四盒" } ] }, { "id": "45", "text": "第二排", "box": [ { "id": "50", "text": "第一盒" }, { "id": "51", "text": "第二盒" }, { "id": "52", "text": "第三盒" }, { "id": "53", "text": "第四盒" }, { "id": "54", "text": "第五盒" } ] } ] }, { "id": "36", "text": "第四层", "line": [ { "id": "55", "text": "第一排", "box": [ { "id": "56", "text": "第一盒" }, { "id": "57", "text": "第二盒" }, { "id": "58", "text": "第三盒" }, { "id": "59", "text": "第四盒" } ] }, { "id": "60", "text": "第二排", "box": [ { "id": "61", "text": "第一盒" }, { "id": "62", "text": "第二盒" }, { "id": "63", "text": "第三盒" } ] } ] } ]

2.遍历方法

        success: function(data) {
                                    var layar = JSON.parse(data.d);//针对于webservice返回的数据
                                    $('.accordion ul li').remove();
                                    for(var i = 0; i < layar.length; i++) { var line = layar[i].line; for(var j = 0; j < line.length; j++) { var box = line[j].box; var a = "<li id = " + line[j].id + " ></li> "; $('.accordion ul').eq(i).append(a); if(box != undefined) { for(var k = 0; k < box.length; k++) { var b = "<div id=" + box[k].id + ">" + box[k].text + "</div>"; $('.accordion ul').eq(i).find("li").eq(j).append(b); } } } } }

 

 

猜你喜欢

转载自www.cnblogs.com/lcf0916/p/9047465.html