将表单字段转换为JSON对象 [英] Convert form fields into JSON object

查看:126
本文介绍了将表单字段转换为JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的格式如下:

<form id="myForm" method="POST">        
    <input type="text" name="matrix[]" value="1"/><br/>
    <input type="text" name="matrix[]" value="2"/><br/>
    <input type="text" name="matrix[]" value="3"/><br/>     
    <input type="text" name="multi_matrix[colors][]" value="red"/><br/>
    <input type="text" name="multi_matrix[colors][]" value="blue"/><br/>        
    <input type="text" name="multi_matrix[weight][]" value="75"/><br/>
    <input type="text" name="multi_matrix[weight][]" value="83"/><br/>      
    <input type="submit" value="Send">
</form>

现在,我想使用JavaScript/jQuery将这些值转换为JSON字符串.当我使用JSON.stringify($(#myForm").serializeArray())代码时,它将返回以下内容:

now I want to use JavaScript/jQuery to convert those values into JSON string. When I use JSON.stringify($("#myForm").serializeArray()) code then it returns the following:

[{"name":"matrix[]","value":"1"},{"name":"matrix[]","value":"2"},{"name":"matrix[]","value":"3"},{"name":"multi_matrix[colors][]","value":"red"},{"name":"multi_matrix[colors][]","value":"blue"},{"name":"multi_matrix[weight][]","value":"75"},{"name":"multi_matrix[weight][]","value":"83"}]

您可以看到所有字段都有一个单独的条目,但是我想将它们结合在一起以得到以下内容:

as you can see all fields have a separate entry, but I want to join them together to get the following:

{"matrix":[1,2,3],"multi_matrix":{"colors":["red","blue"],"weight":[75,83]}}

是否有任何内置功能可以做到这一点?还是我必须遍历所有字段并自己手动创建JSON?

Is there any built-in function that can do this ? Or do I have to iterate through all fields and create JSON manually on my own ?

推荐答案

您可以像在 serializeArray():

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

这篇关于将表单字段转换为JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆