将任意一个jQuery对象进行表单序列化,免除了提交请求时大量拼写表单数据的烦恼,支持键值对格式和JSON格式。

http://zhengxinlong.iteye.com/blog/848712

将任意一个jQuery对象进行表单序列化,免除了提交请求时大量拼写表单数据的烦恼,支持键值对<name&value>格式和JSON格式。

/// <reference name="jquery.js" description="1.3.2版本以上" />

/*!* 扩展jQuery表单序列化函数:{ Version: 1.2, Author: Eric.Zheng, CreateDate: 2010-12-21 }
*
* 消除了jQuery.serialize()只能对form进行序列化的局限
* 该插件可以对任意jQuery对象进行序列化
* 返回数据格式有两种:1.<name&value>(默认)  2.json
*
* 调用方法:$(dom).form_serialize(dataType);
*   参数(可省略):dataType: 默认为html,即返回数据格式为<name&value>;若要返回json格式,则dataType = json;
* 返回数据:序列化表单数据
*
* BUG修复:修复了1.0版本中,多个Dom元素使用同一个name属性时,获取的数据有缺失。
*
**/
(function ($) {
    var formJson = {};
    var currentForm = null;

    $.fn.form_serialize = function (dataType) {
        currentForm = $(this);
        formJson = {};
        var doms = currentForm.find('[name]');
        $.each(doms, function (index, dom) {
            var domName = $(dom).attr('name');
            if (!formJson[domName]) {
                formJson[domName] = { Name: domName, Type: $(dom).attr('type'), Doms: currentForm.find('[name=' + domName + ']') };
            }
        });
        return getResult(dataType);
    };

    var getResult = function (dataType) {
        var d = {
            toJson: function () {
                var data = {};
                $.each(formJson, function (key, json) {
                    data[key] = getVal(json);
                });
                return data;
            },
            toString: function () {
                var val = '';
                var index = 0;
                $.each(formJson, function (key, json) {
                    var prefix = '&';
                    if (index == 0) prefix = '';
                    index++;
                    val += prefix + key + '=' + getVal(json);
                });
                return val;
            }
        };
        return dataType == 'json' ? d.toJson() : d.toString();
    }

    var getVal = function (json) {
        var methods = {
            getDefaultVal: function (dom) {
                return $(dom).val();
            },
            getSelectVal: function (dom) {
                var val = '';
                var selectType = $(dom).attr('type');
                if (selectType == 'select-multiple') {
                    var items = $(dom).val();
                    if (items == null) return '';
                    for (var i = 0; i < items.length; i++) {
                        val += i == 0 ? items[i] : (',' + items[i]);
                    }
                    return val;
                } else {
                    return $(dom).val();
                }
            },
            getRadioVal: function (dom) {
                return $(dom).attr('checked') ? $(dom).val() : null;
            },
            getCheckBoxVal: function (dom) {
                return methods.getRadioVal(dom);
            }
        };

        var dispacher = function (type, dom) {
            switch (type) {
                case 'text':
                case 'password':
                case 'hidden':
                case 'textarea':
                    return methods.getDefaultVal(dom);
                case 'select-one':
                case 'select-multiple':
                    return methods.getSelectVal(dom);
                case 'radio':
                    return methods.getRadioVal(dom);
                case 'checkbox':
                    return methods.getCheckBoxVal(dom);
                default:
                    return '';
            }
        };

        var domType = json.Type;
        var doms = $(json.Doms);
        var count = doms.length;
        if (count > 1) {
            var val = '';
            var index = 0;
            for (var i = 0; i < count; i++) {
                var v = dispacher(domType, doms.eq(i));
                if (v == '' || v == null || v == undefined)
                    continue;
                val += index++ == 0 ? dispacher(domType, doms.eq(i)) : (',' + dispacher(domType, doms.eq(i)));
            }
            return val;
        } else {
            return dispacher(domType, doms);
        }
    };
})(jQuery);