jquery将form参数集成在一个对象中

时间:2013-10-28 03:40:56

标签: javascript jquery ajax

我的页面中有很多表单。我想将它们合并到一个对象中,并在一个对象中提交它们。但是我发现serializeArray()serialize()与我的请求不匹配,serializeArray函数将生成一个数组对象,而且serial模型使用serialize,它不是一个对象。

是否有jquery或local函数可以将它们合并到一个对象中。

我有一个解决方案,但它并不完美,循环serializeArray生成的数组对象,使用$.extend将它们合并到一个对象中。有更好的方法吗?

请帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

我自己找到了解决方案,我模仿了序列化函数并创建了一个简单的插件。如果有任何缺陷,请指出,谢谢

(function($) {
$.fn.paramJson = function(a, traditional) {
    var prefix, s = [], add = function(key, value) {
        // If value is a function, invoke it and return its value
        value = $.isFunction(value) ? value() : (value == null ? ""
                : value);
        s[s.length] = "\"" + encodeURIComponent(key) + "\"" + ":" + "\""
                + encodeURIComponent(value) + "\"";
    };

    // Set traditional to true for jQuery <= 1.3.2 behavior.
    if (traditional === undefined) {
        traditional = $.ajaxSettings
                && $.ajaxSettings.traditional;
    }

    // If an array was passed in, assume that it is an array of form
    // elements.
    if ($.isArray(a) || (a.jquery && !$.isPlainObject(a))) {
        // Serialize the form elements
        $.each(a, function() {
            add(this.name, this.value);
        });

    } else {
        // If traditional, encode the "old" way (the way 1.3.2 or older
        // did it), otherwise encode params recursively.
        for (prefix in a) {
            buildParams(prefix, a[prefix], traditional, add);
        }
    }

    // Return the resulting serialization
    return "{" + s.join(",").replace(r20, "+") + "}";
};
$.fn.serializeJson = function() {
    return $.parseJSON($.paramJson( this.serializeArray()));
};      

})(jQuery的)