我正在使用春季休息。我正在使用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>
感谢您提供任何帮助。
注意。我编辑过问题,如何从用户列表数组中的角色数组中获取角色。
答案 0 :(得分:1)
您应该在每个循环中考虑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>");
});
答案 1 :(得分:0)
$.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) {
答案 2 :(得分:0)
尝试
var data = $.parseJSON(data);
var userListData = data["userlist"];
for (var i=0; i< userListData.length; i++) {
$(".data-contacts-js").append('<tr>\
<td>'+userListData[i].id +'</td>\
<td>'+userListData[i].name+'</td>\
<td>'+ userListData[i].email+'</td>\
</tr>');
}