当窗体包含多个输入数组字段时,是否有更好的解决方案来转换已被jQuery函数serialize()序列化的表单数据。我希望能够将表单数据转换为JSON对象以重新创建其他一些信息丰富的表格。所以告诉我一个更好的方法来获取序列化字符串转换为JSON对象。如何将jQuery.serialize()数据转换为JSON对象?
<form id='sampleform'>
<input name='MyName' type='text' /> // Raf
<!--array input fields below-->
<input name='friendname[]' type='text' /> // Bily
<input name='fiendemail[]' type='text' /> // [email protected]
<!--duplicated fields below to add more friends -->
<input name='friendname[]' type='text' /> // Andy
<input name='fiendemail[]' type='text' /> // [email protected]
<input name='friendname[]' type='text' /> // Adam
<input name='fiendemail[]' type='text' /> // [email protected]
</form>
jQuery的方法适用于获取数据
var MyForm = $("#sampleform").serialize();
/** result : MyName=Raf&friendname[]=Billy&fiendemail[][email protected]&friendname[]=Andy&fiendemail[][email protected]&friendname[]=Adam&fiendemail[][email protected]
*/
如何使这个数据到一个JSON对象? 它应该从上面的表单中获得以下示例JSON数据。
{
"MyName":"raf",
"friendname":[
{"0":"Bily"},
{"1":"Andy"},
{"2":"Adam"}
],
"friendemail":[
{"0":"[email protected]"},
{"1":"[email protected]"},
{"2":"[email protected]"}
]
}
从技术上讲,这不是基于您的查询字符串格式化JSON对象的方式。具体来说,数组元素不会是具有索引的对象,而只是值。这样说,如果你需要你发布的格式,你可能需要编写一个自定义函数。 – 2010-07-18 23:28:02
可能重复[序列化形式JSON与jQuery](http://stackoverflow.com/questions/1184624/serialize-form-to-json-with-jquery) – SLaks 2010-07-18 23:38:09
谢谢Slaks和杰森,是的,我同意我需要一个功能去做,而Slaks已经为我指出了这一点。 – Raftalks 2010-07-19 00:23:41