zoukankan      html  css  js  c++  java
  • 原生JS表单序列化

    // 表单序列化,IE9+
    HTMLFormElement.prototype.serialize = function() {
        var form = this;
        // 表单数据
        var arrFormData = [], objFormData = {};
    
        [].slice.call(form.elements).forEach(function(ele) {
            // 元素类型和状态
            var type = ele.type, disabled = ele.disabled;
    
            // 元素的键值
            var name = ele.name, value = encodeURIComponent(ele.value || 'on');
    
            // name参数必须,元素非disabled态,一些类型忽略
            if (!name || disabled || !type || (/^reset|submit|image$/i.test(type)) || (/^checkbox|radio$/i.test(type) && !ele.checked)) {
                return;
            }
    
            type = type.toLowerCase();
    
            if (type !== 'select-multiple') {
                if (objFormData[name]) {
                    objFormData[name].push(value);
                } else {
                    objFormData[name] = [value];
                }
            } else {
                [].slice.call(ele.querySelectorAll('option')).forEach(function(option) {
                    var optionValue = encodeURIComponent(option.value || 'on');
                    if (option.selected) {
                        if (objFormData[name]) {
                            objFormData[name].push(optionValue);
                        } else {
                            objFormData[name] = [optionValue];
                        }
                    }
                });
            }                
        });
    
        for (var key in objFormData) {
            arrFormData.push(key + '=' + objFormData[key].join());
        }
    
        return arrFormData.join('&');    
    };
  • 相关阅读:
    关于博客
    latex句首缩进空格
    javable 之Iterable
    javable之Comparable
    常量池与Integer和String的“==”
    静态多态与动态多态
    String和StringBuilder效率不同的原理
    equals和hashcode
    Eclipse里面使用checkstyle(Google style)
    矩阵链乘问题
  • 原文地址:https://www.cnblogs.com/chenzeyongjsj/p/7245570.html
Copyright © 2011-2022 走看看