Reputation: 597
I am using spring rest .I am getting valid json .
{
"userlist":[
{
"id":2,
"email":"[email protected]",
"password":"$2a$10$41f83FwKhR9OWNFFeBeV0u.dMIy48HsIiA6o/icgKW2nmbQyPzsby",
"name":"waqas",
"lastName":"kamran",
"active":1,
"roles":[
{
"id":2,
"role":"user",
"new":false
}
],
"new":false
},
{
"id":3,
"email":"[email protected]",
"password":"$2a$10$pAZljuoMMXVALDpyOQtmletT0XbS2bn8ENEa7DxfgYQyFeLvpklRa",
"name":"waqar",
"lastName":"kamran",
"active":1,
"roles":[
{
"id":2,
"role":"user",
"new":false
}
],
"new":false
},
{
"id":4,
"email":"[email protected]",
"password":"$2a$10$fpQagNnB79JRsdFJBuMiDOw3E2F8OSopmfAGyA2RuurM63vWC/CCm",
"name":"waqas",
"lastName":"kamran",
"active":1,
"roles":[
{
"id":1,
"role":"admin",
"new":false
}
],
"new":false
},
{
"id":5,
"email":"[email protected]",
"password":"$2a$10$LXWJP2mVsD/s3xhZrmnhOerPPCTguDXBqwXwihPWIBMF0jgufuBRu",
"name":"naila",
"lastName":"naseem",
"active":1,
"roles":[
{
"id":1,
"role":"admin",
"new":false
}
],
"new":false
},
{
"id":6,
"email":"[email protected]",
"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
}
]
}
now i am trying to use jquery for each loop to show result but unable to do that . i am little bit confused about nested array .
i am using following js code. actually i am new to 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>
thanks for any kind of help .
note . i have edited question , how can i get role from roles array that is inside userlist array .
Upvotes: 0
Views: 1028
Reputation: 19164
$.get()
return string, you need to parse to JSON
var data = JSON.parse(data)
$.each(data.userlist, function(i, contact) {...
or using $.getJSON()
to return as JSON object
$.getJSON("http://localhost:8080/contacts", function(data) {
$.each(data.userlist, function(i, contact) {
Upvotes: 0
Reputation: 6565
You should consider userlist
in each loop. Like this:
$.each(data.userlist, function(i, contact) {
$(".data-contacts-js").append(
"<tr><td>" + contact.id + "</td>" +
"<td>" + contact.name+ "</td>" +
"<td>" + contact.email + "</td></tr>");
});
Upvotes: 1