如何使用 REST 服务 URL 从嵌套的 JSON 读取数据



我正在使用春休。我正在获得有效的 json.

{  
"userlist":[  
{  
"id":2,
"email":"waqasrana11@gmail.com",
"password":"$2a$10$41f83FwKhR9OWNFFeBeV0u.dMIy48HsIiA6o/icgKW2nmbQyPzsby",
"name":"waqas",
"lastName":"kamran",
"active":1,
"roles":[  
{  
"id":2,
"role":"user",
"new":false
}
],
"new":false
},
{  
"id":3,
"email":"waqar11@gmail.com",
"password":"$2a$10$pAZljuoMMXVALDpyOQtmletT0XbS2bn8ENEa7DxfgYQyFeLvpklRa",
"name":"waqar",
"lastName":"kamran",
"active":1,
"roles":[  
{  
"id":2,
"role":"user",
"new":false
}
],
"new":false
},
{  
"id":4,
"email":"waqas111@hotmail.com",
"password":"$2a$10$fpQagNnB79JRsdFJBuMiDOw3E2F8OSopmfAGyA2RuurM63vWC/CCm",
"name":"waqas",
"lastName":"kamran",
"active":1,
"roles":[  
{  
"id":1,
"role":"admin",
"new":false
}
],
"new":false
},
{  
"id":5,
"email":"nailanaseem111@gmail.com",
"password":"$2a$10$LXWJP2mVsD/s3xhZrmnhOerPPCTguDXBqwXwihPWIBMF0jgufuBRu",
"name":"naila",
"lastName":"naseem",
"active":1,
"roles":[  
{  
"id":1,
"role":"admin",
"new":false
}
],
"new":false
},
{  
"id":6,
"email":"zain11@gmail.com",
"password":"$2a$10$CxYTDaJ.HUVbNCT8RGg1a.DISG2xGcQ8azV2YwOwlT6MRdPBCjgbK",
"name":"zain",
"lastName":"haq",
"active":1,
"roles":[  
{  
"id":2,
"role":"user",
"new":false
}
],
"new":false
}
],
"roleList":[  
{  
"id":1,
"role":"admin",
"new":false
},
{  
"id":2,
"role":"user",
"new":false
}
]
}

现在我正在尝试为每个循环使用 jQuery 来显示结果,但无法做到这一点。 我对嵌套数组有点困惑。

我正在使用以下JS代码。 其实我是jquery的新手。

<table class="data-contacts-js table table-striped" >
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
</tr>
</table>
<button id="fetchContacts" class="btn btn-default" type="submit">show users</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$("#fetchContacts").bind("click", function() {
$.get("http://localhost:8080/contacts", function(data) {
$.each(data, function(i, contact) {
$(".data-contacts-js").append(
"<tr><td>" + contact.id + "</td>" +
"<td>" + contact.name+ "</td>" +
"<td>" + contact.email + "</td></tr>");
});
});
});
</script>

感谢您的任何帮助.

注意。 我编辑了问题,如何从用户列表数组内的角色数组中获取角色。

您应该在每个循环中考虑userlist。喜欢这个:

$.each(data.userlist, function(i, contact) {
$(".data-contacts-js").append(
"<tr><td>" + contact.id + "</td>" +
"<td>" + contact.name+ "</td>" +
"<td>" + contact.email + "</td></tr>");
});

$.get()返回字符串,你需要解析为 JSON

var data = JSON.parse(data)
$.each(data.userlist, function(i, contact) {...

或使用$.getJSON()作为 JSON 对象返回

$.getJSON("http://localhost:8080/contacts", function(data) {
$.each(data.userlist, function(i, contact) {

相关内容

  • 没有找到相关文章

最新更新