Reputation: 665
I'm writing ajax post request. The problem is that i don't know how to loop throught json. on success i got this function:
.done(function ( data ) {
$('#records').append(data);
});
And it prints content into my #records like this:
0: {id: 1, user_id: 1, title: "first", created_at: "2015-05-15 06:50:21",…}
1: {id: 2, user_id: 2, title: "second", created_at: "2015-05-15 06:50:38",…}
2: {id: 3, user_id: 3, title: "third", created_at: "2015-05-15 06:50:41",…}
3: {id: 4, user_id: 4, title: "fourth", created_at: "2015-05-15 06:50:45",…}
How do i loop throught id's and pick it's content (1,2,3,4)? Thanks in advance!
Upvotes: 0
Views: 48
Reputation: 2336
You can do like this :
.done(function ( data ) {
//We declare the target element in a variable for better perfs
var target = $('#records');
//We loop in the returned array
data.forEach(function(elt) {
//Here the elt variable represents an item of your JSON array
//You can access to item properties with the . (ex : elt.id, elt.title,...)
target.append("<h2>"+elt.title+"</h2>");
});
});
Upvotes: 0
Reputation: 7907
.done(function ( data ) {
$.each(data, function(item) {
$('#records').append(item.id);
});
});
Upvotes: 1