2013-03-03 59 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