循环通过json

时间:2015-05-15 11:40:21

标签: javascript ajax json laravel

我正在撰写ajax post请求。问题是我不知道如何循环json。成功后我得到了这个功能:

.done(function ( data ) {
  $('#records').append(data);
});

它将内容打印到我的#records中:

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",…}

我如何循环访问id并选择它的内容(1,2,3,4)? 提前谢谢!

2 个答案:

答案 0 :(得分:1)

.done(function ( data ) {
    $.each(data, function(item) {
        $('#records').append(item.id);
    });

});

答案 1 :(得分:0)

你可以这样做:

.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>");
  });  
});

forEach function reference