jQuery表单序列化问题

/// <reference name="jquery.js" description="1.3.2版本以上" />
/*!* 扩展jQuery表单序列化函数:{ Version: 1.0, Author: Eric.Zheng, CreateDate: 2010-11-29 }
* 消除了jQuery.serialize()只能对form进行序列化的局限,
* 该插件可以对任意jQuery对象进行序列化,按照<name&value>形式配对。
*
* 调用方法:$(dom).form_serialize();
* 返回数据:例如 name=AA&age=20&gender=男
**/
(function ($) {
    var formJson = {};

    var addDom = function (dom) {
        var json = { Name: $(dom).attr('name'), Type: $(dom).attr('type'), Dom: $(dom) };
        formJson[$(dom).attr('name')] = json;
    };

    var getVal = function (dom) {
        var methods = {
            getDefaultVal: function (dom) {
                return $(dom).val();
            },
            getRadioVal: function (domName) {
                var doms = document.getElementsByName(domName);
                if (!doms) return '';
                for (var i = 0; i < doms.length; i++) {
                    if (doms[i].checked) return doms[i].value;
                }
                return '';
            },
            getCheckBoxVal: function (domName) {
                var val = '';
                var doms = document.getElementsByName(domName);
                if (!doms) return val;

                var index = 0;
                for (var i = 0; i < doms.length; i++) {
                    if (doms[i].checked) {
                        if (index == 0) {
                            val += doms[i].value;
                        }
                        else {
                            val += ',' + doms[i].value;
                        }
                        index++;
                    }
                }
                return val;
            }
        };

        var type = $(dom).attr('type');
        var domName = $(dom).attr('name');

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

    $.fn.form_serialize = function () {
        var val = '';
        $(this).find('[name]').each(function () {
            addDom(this);
        });

        var index = 0;
        $.each(formJson, function () {
            var prefix = '&';
            if (index == 0) prefix = '';
            index++;
            val += prefix + this.Name + '=' + getVal(this.Dom);
        });
        return val;
    };
})(jQuery);

你可能感兴趣的:(jquery,json)