Reputation:
I have some JSON like:
response = [
{"FIRSTNAME":"Richard","ACCOUNT":5555,"ID":"5056","LASTNAME":"Harris"},
{"FIRSTNAME":"Gary","ACCOUNT":4444,"ID":"DFC7","LASTNAME":"Coles"},
{"FIRSTNAME":"Jeff","CORPORATEACCOUNT":3333,"ID":"7F31","LASTNAME":"Hopper"},
{"FIRSTNAME":"Jack","ACCOUNT":2222,"ID":"E051","LASTNAME":"Canrell"},
{"FIRSTNAME":"Tim","ACCOUNT":1111,"ID":"5056","LASTNAME":"Johns"}
]
I need to loop over it and display a row for each user, and my jQuery isn't working. What am I doing wrong?
$.ajax({
type: "POST",
url: "/my-controller/my-method?format=json",
data: {id: id},
dataType: "json",
success: function(response) {
var resultHtml = '';
$.each(response, function(i, response) {
$.each(response, function(property, value) {
resultHtml += value + '\n';
});
});
alert(resultHtml);
}
});
So this echos out:
Richard
5555
5056
Harris
Gary
4444
DFC7
Coles
etc.
etc.
etc.
The JSON is being returns from the controller but how do I loop through and get this?
Richard harris 5555 5056
Gary Coles 4444 DFC7
Jeff Hopper 3333 7F31
Jack Canrell 2222 E051
Tim Johns 1111 5060
Upvotes: 1
Views: 109
Reputation: 11042
$.ajax({
type: "POST",
url: "/my-controller/my-method?format=json",
data: {id: id},
dataType: "json",
success: function(response) {
var resultHtml = '';
$.each(response, function(i, row) {
resultHTML += row.FIRSTNAME + " " + row.LASTNAME + " " + row.ACCOUNT + " " + row.ID + "\n";
});
alert(resultHtml);
}
});
Upvotes: 0
Reputation: 227240
You don't need to $.each
a 2nd time. You have an object, just use the fields you want.
$.each(response, function(i, value) {
resultHtml += value.FIRSTNAME + value.LASTNAME + value.ACCOUNT + value.ID + '\n';
});
Upvotes: 8
Reputation: 4314
You need to parse the JSON first, try JSON.parse(response); to have it create an object you can iterate over.
Upvotes: 0