继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

JQ如何获取多层JSON的数据 2层解释?

qaytix
关注TA
已关注
手记 104
粉丝 37
获赞 165

www.zhihu.com/question/25147806/answer/30178499

  • 代码如下:JSON:test.json{

"programmers": [
{
"firstName": "Brett",
"lastName": "McLaughlin",
"email": "aaaa"
},
{
"firstName": "Jason",
"lastName": "Hunter",
"email": "bbbb"
},
{
"firstName": "Elliotte",
"lastName": "Harold",
"email": "cccc"
}
],
"authors": [
{
"firstName": "Isaac",
"lastName": "Asimov",
"genre": "science fiction"
},
{
"firstName": "Tad",
"lastName": "Williams",
"genre": "fantasy"
},
{
"firstName": "Frank",
"lastName": "Peretti",
"genre": "christian fiction"
}
],
"musicians": [
{
"firstName": "Eric",
"lastName": "Clapton",
"instrument": "guitar"
},
{
"firstName": "Sergei",
"lastName": "Rachmaninoff",
"instrument": "piano"
}
]
}

### HTML: test.html<!Doctype html>

```<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
    table{   border-collapse:collapse;
                    color:#333;
                    border:1px solid #333;
}
    td,th{
                line-height:1.5em;
                padding:3px 5px;
                text-align:left;
                border:1px solid #333;
}
    th{
            font-size:1.3em;
            line-height:1.8em;
            color:#f00;
}
    .tit{
        font-weight:bold;
}
</style>
</head>
<body>
<button id="btn">加载</button>
<br />
<br />
<table id="test" border="1" width="800">

</table>
<script type="text/javascript">
    $("#btn").click(function(){
        var html="";
        $.getJSON("test.json",function(data){
            $.each(data,function(Name,db){
                html+="<tr><th colspan='6'>"+Name+"</th></tr>";
                var jsonarray =db;
                for(var i =0;i<jsonarray.length;i++){
                    var jsonobj = jsonarray[i];
                    html+="<tr>";
                    for(var x in jsonobj){
                        html+="<td class='tit'>"+x+"</td><td>"+jsonobj[x]+"</td>"
                    }
                    html+="</tr>";
                }
            })
            $("#test").html(html);
        })
    })

</script>
</body>
</html>
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP