2013-03-03 85 views
0

我已經輸入字段的表格如下:無法通過JSON數組循環,jQuery的

<form "data-qustion_form"=true> 
    <input name="question[description]" value="quesd"> 
    <input name="question[answers][0][description]" value="ansd1"> 
    <input name="question[answers][1][description]" value="ansd2"> 
</form> 

我使用https://github.com/marioizquierdo/jquery.serializeJSON表單數據轉換成JSON。也嘗試使用https://stackoverflow.com/a/8407771/707636。兩者都很好。但是我無法循環瀏覽json中的數組。

我下面的js

$("[data-question_form]").on("submit", function(e) { 
    var o = $(this).serializeObject(); // $(this).serializeJSON(); both results same 
    console.log(o); 
    console.log(o["question"]); 
    console.log(o["question"]["answers"]); 
    $.each(question["answers"], function() { 
    console.log("print test"); // I don't see this on console in Chrome inspector 
    } 
    e.preventDefault(); 
} 

上使用Chrome檢查控制檯輸出如下:

Object {utf8: "✓", question: Object} 
Object {description: "quesd", answers: Array[0]} 
[1362289041238: Object, 1362289045644: Object] 

進一步擴大[1362289041238: Object, 1362289045644: Object]顯示length: 0

如何遍歷這個數組來讀取jQuery中的每個答案描述?

+0

'$。每個(問題[ 「答案」],函數(){'看來我錯了。 – jchapa 2013-03-03 05:57:26

+0

我也嘗試'$。每個(問題[ 「答案」],功能(K,V ){console.log(v);}',沒有工作 – Bongs 2013-03-03 05:58:59

回答

0

好吧,我剛剛解決了它,但在輸入元素的name屬性中做了一些小改動。櫃檯前加入[]如下:

<input name="question[answers][][0][description]" value="ansd1"> 
<input name="question[answers][][1][description]" value="ansd2"> 

現在我可以遍歷它:)

1

我無法找到任何問題與您的代碼(見example),或者使用serializeObject - 使用鏈接答案中的代碼 - 或使用serializeJSON - 與來自GitHub的代碼。您的標記,但是,不得不進行調整:

<form "data-qustion_form"=true> 

到:

<form data-question_form="true"> 

附:正如@jchapa指出的那樣,question["answers"]也是錯誤的 - 括號沒有平衡。但我假設它只是你在這裏粘貼的代碼,你的實際代碼必須是正確的(否則你根本得不到任何結果)。

$.each(o["question"]["answers"], function() { 
    console.log("print test"); // I don't see this on console in Chrome inspector 
    }); 
}); 
+1

很好的答案 - 推到10k;) – jchapa 2013-03-03 07:42:29

+0

@jchapa哈哈非常感謝! – mgibsonbr 2013-03-03 07:43:45