{ "id": "36", "title": "Dr","firstname": "Ian", "lastname": "Fletcher", "permissions": { "permissionlist": [{ "title": "Images", "accessid": "152"},{ "title": "Documents", "accessid": ""}] } }
I have an ajax callback with the above data and need some help in getting some of the data out.
I have managed to get the data out of the callback data eg id, title firstname, lastname, but am struggling to get the permissions out.
success: function(data) {
jQuery.each(data, function(index, itemData) {
$('#<%=txtTitle.ClientID %>').val(itemData.title);
$('#<%=txtFirstName.ClientID %>').val(itemData.firstname);
$('#<%=txtSurname.ClientID %>').val(itemData.lastname);
jQuery.each(itemData.permissions, function(index, permissionData) {
alert(permissionData.title);
});
});
}
I have attempted to use the each function using the permissions as the list but the alert is always displaying undefined. Where am I going wrong with this?
itemData.permissions
is an object, not an array. The array is in the property permissionlist
.
jQuery.each(itemData.permissions.permissionlist, function(index, permissionData) {
alert(permissionData.title);
});
You are iterating over the wrong property, inside permissions you still have a permissionList:
jQuery.each(itemData.permissions.permissionList, function(index, permissionData) {
alert(permissionData.title);
});
permissions
is an object that has a permissionList
element that contains an array of objects. You are not iterating over the array, but over the permissionlist
object itself. Use:
jQuery.each(itemData.permissions.permissionlist)
You could also use permissionData[0].title
, but that only gets the first title.
I've seen a question like this asked enough times to create this: https://github.com/ajcrites/json-visualize/
You can see it used for this question here: http://jsfiddle.net/4cb2b/
data
is the object returned from the ajax call. Loop through the properties at each level and you will see the structure
function success(data) {
// data
jQuery.each(data, function (index, itemData) {
alert('index=' + index + ', itemData=' + itemData);
});
// data.permissions
jQuery.each(data.permissions, function (index, itemData) {
alert('index=' + index + ', itemData=' + itemData);
});
// data.permissions.permissionlist
jQuery.each(data.permissions.permissionlist, function (index, itemData) {
alert('index=' + index + ', itemData=' + itemData);
});
// ...
}
success(data);
JSFiddle for testing
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.