我做了一個jQuery的.ajax調用,我期待json的結果。 問題是,如果有5位作者說,我會得到author_details_0,author_details_1,author_details_2等....我怎樣才能動態構建變量的名稱從json中檢索?我不知道我會得到多少位作者,可能會有數百位。Jquery Json動態變量名稱生成
$.ajax({
type: "POST",
url: "/authordetails/show_my_details/",
data: af_pTempString,
dataType: "json",
beforeSend: function() {
},
success: function(jsonData) {
console.log("Incoming from backend : " + jsonData.toSource());
if(jsonData.AuthorCount)
{
console.log("Number of Authors : " + jsonData.AuthorCount);
for (i = 0; i < jsonData.AuthorCount; i++)
{
temp = 'author_details_' + i; <-------------------This is the name of the variable I'm expecting.
console.log("Farm information : " + eval(jsonData.temp)); <----- This doesn't work, how can I get jsonData.author_details_2 for example, 'coz I don't know how many authors are there, there could be hundreds.
}
}
請讓我知道,如果你有任何想法如何解決這個問題! 非常感謝。
爲什麼你需要author_details_0,1,2,等等? – yoda 2009-09-27 03:00:18
你是如何生成json的? – Eric 2009-09-27 18:52:01
我在後端使用dJango。我創建的數據模型具有作者和相關的Author_Details表。給定發佈者ID,我查詢並獲取我簡單序列化的作者集 - json_serializer.serialize(allAuthors,ensure_ascii = False)。 這不會序列化作者詳細信息,因此我必須遍歷作者對象數組並手動創建它們,因此author_details_XX其中XX是作者主鍵。 我不確定是否有辦法將Author和其他細節綁定爲單個JSON Array對象。如果有的話,我會很高興地翻新我的代碼,因爲它更乾淨。 – PlanetUnknown 2009-12-18 18:50:31