格式化serializeArray

时间:2012-07-28 16:29:39

标签: jquery

jQuery.serializeArray当前返回此结果:

[Object { name="id",  value="0"}, Object { name="gender[]",  value="1"}, Object { name="gender[]",  value="2"}, Object { name="countries[]",  value="AU"}, Object { name="countries[]",  value="GB"}, Object { name="ages[]",  value="25"}, Object { name="ages[]",  value="99"}]

我希望以这种方式格式化结果:

{id: 0, gender: ['1', '2'], countries: ['AU', 'GB'], ages: ['25', '99']}

如何实现这一目标?

我不喜欢serializeArray如何格式化它的输出,我创建了以更可接受的方式格式化它的函数。

(function( $ ){
$.fn.serializeJSON=function() {
    var json = {}, propname;
    $.each($(this).serializeArray(), function(index, n){
        propname = n.name.replace('[]', '');
        if (!json.hasOwnProperty(propname))
        {
            json[propname] = n.value;
        }
        else if( ! (json[propname] instanceof Array) )
        {
            json[propname] = new Array(json[propname], n.value);
        }
        else
        {
            json[propname].push(n.value);
        }
    });
    return json;
}; 
})(jQuery);

创建表单后,只需将这段代码放在某处:

$('#form_id').submit(function(e) {
    e.preventDefault();
    e.stopPropagation();
    var data = $(this).serializeJSON();
    console.log(data);
})

我希望那些喜欢将表单发布到PHP的人会有所帮助。

1 个答案:

答案 0 :(得分:0)

我用这个:

$.fn.serializeObject = function(options) {

    options = $.extend({}, options);

    var self = this,
        json = {},
        push_counters = {},
        patterns = {
            "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
            "key":      /[a-zA-Z0-9_\sąćęłóśżźĄĆĘŁÓŚŻŹ\/-]+|(?=\[\])/g,
            "push":     /^$/,
            "fixed":    /^\d+$/,
            "named":    /^[a-zA-Z0-9_]+$/
        };


    this.build = function(base, key, value){
        base[key] = value;
        return base;
    };

    this.push_counter = function(key){
        if(push_counters[key] === undefined){
            push_counters[key] = 0;
        }
        return push_counters[key]++;
    };

    $.each($(this).serializeArray(), function(){
        var k,
            keys = this.name.match(patterns.key),
            merge = this.value,
            reverse_key = this.name;

        while((k = keys.pop()) !== undefined){
            reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');

            merge = self.build({}, k, merge);
        }
        json = $.extend(true, json, merge);
    });

    return json;
};