2015-05-15 39 views
0

我在寫ajax post請求。問題是我不知道如何循環json。成功我得到這個功能:循環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",…} 

我怎麼循環throught的ID,並選擇它的內容(1,2,3,4 )? 在此先感謝!

+0

[找到答案在這裏] [1] [1]:http://stackoverflow.com/questions/2342371/jQuery-loop-on-json-data-using-each 你需要使用$ .each()函數或者檢入jquery文檔 –

+0

你s可能看看這個線程 http://stackoverflow.com/questions/27478808/get-specfic-response-from-mysql-in-jquery-ajax-success – Matarishvan

回答

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

});

+0

你能提供一些更多的信息? –

+0

肯定只是,這使用jQuery來遍歷JSON數組。每個項目將被表示爲「項目」,因此項目將具有所有可用的屬性,item.id,item.title等... – PythonIsGreat

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