如何将 jQuery.serialize() 数据转换为 JSON 对象?

2024-02-07

当表单包含多个输入数组字段时,是否有更好的解决方案来转换已通过 jQuery 函数 serialize() 序列化的表单数据。我希望能够将表单数据转换为 JSON 对象,以重新创建一些其他信息表。那么告诉我一个更好的方法来将序列化字符串转换为 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] /cdn-cgi/l/email-protection

    <!--duplicated fields below to add more friends -->
    <input name='friendname[]' type='text' /> // Andy
    <input name='fiendemail[]' type='text' /> // [email protected] /cdn-cgi/l/email-protection

    <input name='friendname[]' type='text' /> // Adam
    <input name='fiendemail[]' type='text' /> // [email protected] /cdn-cgi/l/email-protection
</form>

应用jquery方法获取数据

var MyForm = $("#sampleform").serialize();
/** result : MyName=Raf&friendname[]=Billy&fiendemail[][email protected] /cdn-cgi/l/email-protection&friendname[]=Andy&fiendemail[][email protected] /cdn-cgi/l/email-protection&friendname[]=Adam&fiendemail[][email protected] /cdn-cgi/l/email-protection
*/

如何将此数据放入 JSON 对象? 其中应该包含来自上述表单的以下示例 JSON 数据。

{
    "MyName":"raf",
    "friendname":[
        {"0":"Bily"},
        {"1":"Andy"},
        {"2":"Adam"}
    ],
    "friendemail":[
        {"0":"[email protected] /cdn-cgi/l/email-protection"},
        {"1":"A[email protected] /cdn-cgi/l/email-protection"},
        {"2":"[email protected] /cdn-cgi/l/email-protection"}
    ]
}

var formdata = $("#myform").serializeArray();
var data = {};
$(formdata ).each(function(index, obj){
    data[obj.name] = obj.value;
});

简单又快速;)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 jQuery.serialize() 数据转换为 JSON 对象? 的相关文章

随机推荐