3

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 的人有所帮助。

4

1 回答 1

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;
};
于 2013-01-29T15:18:08.327 回答