如何将表单的所有元素转换为JavaScript对象?

我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;


当前回答

这会把一切都考虑在内

函数formToObject(表单){let data=新FormData(表单);let queryString=新URLSearchParams(data).toString();var obj={};var params=queryString.split(“&”);对于(var i=0;i<params.length;i++){var param=params[i].split(“=”);var key=param[0].replace(“[]”,“”);var key=密钥.替换(“%5B%5 D”,“”);var值=参数[1];if(obj[key]==未定义){obj[key]=值;}else if(数组的obj[key]实例){obj[key].push(值);}其他{obj[key]=[obj[key],值];}}控制台日志(obj)返回obj;}<!DOCTYPE html><html><head><title>表单示例</title></head><body style=“height:800px;溢出:滚动”><form id=“test”onchange=“formToObject(this)”><div><h3>水果</h3><input type=“checkbox”name=“fruit”value=“apple”id=“apple“><label for=“apple”>Apfel</label><input-type=“checkbox”name=“fruit”value=“banana”id=“banana“><label for=“banana”>Banane</label><input type=“checkbox”name=“fruit”value=“cherry”id=“cherr”><label for=“cherry”>Kirsche</label><input type=“checkbox”name=“fruit”value=“葡萄”id=“葡萄”><label for=“葡萄”>Traube</label><input type=“checkbox”name=“fruit”value=“pear”id=“pear“><label for=“pear”>Birne</label></div><div><h3>多个选项</h3><select multiple name=“manyOptions[]”><option value=“选项1”>选项1</option><option value=“option 2”>选项2</option><option value=“选项3”>选项3</option></选择></div><div><h3>检查选项</h3><input type=“radio”name=“onceOption”value=“Option 1”>选项1<br><input type=“radio”name=“onceOption”value=“Option 2”>选项2<br><input type=“radio”name=“onceOption”value=“Option 3”>选项3<br></div></form></body></html>

其他回答

此代码转换并保存输入类型,而不是全部转换为字符串:

jQuery.fn.serializeForm = function () {
    var form = this.get(0);
    var i = [];
    var ret = {};
    for (i = form.elements.length - 1; i >= 0; i = i - 1) {
        if (form.elements[i].name === "") {
            continue;
        }
        var name = form.elements[i].name;
        switch (form.elements[i].nodeName) {
            case 'INPUT':
                switch (form.elements[i].type) {
                    case 'text':
                    case 'tel':
                    case 'email':
                    case 'hidden':
                    case 'password':
                        ret[name] = encodeURIComponent(form.elements[i].value);
                        break;
                    case 'checkbox':
                    case 'radio':
                        ret[name] = form.elements[i].checked;
                        break;
                    case 'number':
                        ret[name] = parseFloat(form.elements[i].value);
                        break;
                }
                break;
            case 'SELECT':
            case 'TEXTAREA':
                ret[name] = encodeURIComponent(form.elements[i].value);
                break;
        }
    }
    return ret;
};

例如,这是输出:

Day: 13
Key: ""
Month: 5
OnlyPayed: true
SearchMode: "0"
Year: 2021

而不是

Day: "13"
Key: ""
Month: "5"
OnlyPayed: "true"
SearchMode: "0"
Year: "2021"

serialize函数将JSON对象作为参数并返回serialize String。

function serialize(object) {
            var _SPECIAL_CHARS = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, _CHARS = {
                '\b' : '\\b',
                '\t' : '\\t',
                '\n' : '\\n',
                '\f' : '\\f',
                '\r' : '\\r',
                '"' : '\\"',
                '\\' : '\\\\'
            }, EMPTY = '', OPEN_O = '{', CLOSE_O = '}', OPEN_A = '[', CLOSE_A = ']', COMMA = ',', COMMA_CR = ",\n", CR = "\n", COLON = ':', space = "", COLON_SP = ': ', stack = [], QUOTE = '"';
            function _char(c) {
                if (!_CHARS[c]) {
                    _CHARS[c] = '\\u' + ('0000' + (+(c.charCodeAt(0))).toString(16))
                        .slice(-4);
                }
                return _CHARS[c];
            }
            function _string(s) {
                return QUOTE + s.replace(_SPECIAL_CHARS, _char) + QUOTE;
                // return str.replace('\"','').replace('\"','');
            }

            function serialize(h, key) {
                var value = h[key], a = [], colon = ":", arr, i, keys, t, k, v;
                arr = value instanceof Array;
                stack.push(value);
                keys = value;
                i = 0;
                t = typeof value;
                switch (t) {
                    case "object" :
                        if(value==null){
                            return null;
                        }
                        break;
                    case "string" :
                        return _string(value);
                    case "number" :
                        return isFinite(value) ? value + EMPTY : NULL;
                    case "boolean" :
                        return value + EMPTY;
                    case "null" :
                        return null;
                    default :
                        return undefined;
                }
                arr = value.length === undefined ? false : true;

                if (arr) { // Array
                    for (i = value.length - 1; i >= 0; --i) {
                        a[i] = serialize(value, i) || NULL;
                    }
                }
                else { // Object
                    i = 0;
                    for (k in keys) {
                        if (keys.hasOwnProperty(k)) {
                            v = serialize(value, k);
                            if (v) {
                                a[i++] = _string(k) + colon + v;
                            }
                        }
                    }
                }

                stack.pop();
                if (space && a.length) {

                    return arr
                        ? "[" + _indent(a.join(COMMA_CR), space) + "\n]"
                        : "{\n" + _indent(a.join(COMMA_CR), space) + "\n}";
                }
                else {
                    return arr ? "[" + a.join(COMMA) + "]" : "{" + a.join(COMMA)
                        + "}";
                }
            }
            return serialize({
                "" : object
            }, "");
        }

此线程似乎已成为表单序列化的常见问题解答:)

我对PHP命名的看法:<input name=“user[name]”>

$('form').on('submit', function(ev) {
   ev.preventDefault();

   var obj = $(this).serializePHPObject();

   // $.post('./', obj);
});
(function ($) {
  // based on https://stackoverflow.com/a/25239999/1644202

  // <input name="user[name]" >
  $.fn.serializePHPObject = function () {
    var obj = {};
    $.each(this.serializeArray(), function (i, pair) {
      var cObj = obj,
        pObj,
        cpName;
      $.each(pair.name.split("["), function (i, pName) {
        pName = pName.replace("]", "");
        pObj = cObj;
        cpName = pName;
        cObj = cObj[pName] ? cObj[pName] : (cObj[pName] = {});
      });
      pObj[cpName] = pair.value;
    });
    return obj;
  };
})(jQuery);

这里有一种非jQuery方法:

    var getFormData = function(form) {
        //Ignore the submit button
        var elements = Array.prototype.filter.call(form.elements, function(element) {
            var type = element.getAttribute('type');
            return !type || type.toLowerCase() !== 'submit';
        });

您可以这样使用:

function() {

    var getFormData = function(form) {
        //Ignore the submit button
        var elements = Array.prototype.filter.call(form.elements, function(element) {
            var type = element.getAttribute('type');
            return !type || type.toLowerCase() !== 'submit';
        });

        //Make an object out of the form data: {name: value}
        var data = elements.reduce(function(data, element) {
            data[element.name] = element.value;
            return data;
        }, {});

        return data;
    };

    var post = function(action, data, callback) {
        var request = new XMLHttpRequest();
        request.onload = callback;
        request.open('post', action);
        request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        request.send(JSON.stringify(data), true);
        request.send();
    };

    var submit = function(e) {
        e.preventDefault();
        var form = e.target;
        var action = form.action;
        var data = getFormData(form);
        //change the third argument in order to do something
        //more intersting with the response than just print it
        post(action, data, console.log.bind(console));
    }

    //change formName below
    document.formName.onsubmit = submit;

})();

我检查了所有其他答案是否存在问题,如果输入名称是数组,例如name[key],那么应该这样生成:

名称:{key:value}


例如:如果您的HTML表单与下面的表单类似:

<form>
    <input name="name" value="value" >
    <input name="name1[key1]" value="value1" >
    <input name="name2[key2]" value="value2" >
    <input name="name3[key3]" value="value3" >
</form>

但是它应该像下面的JSON一样生成,而不是像下面这样的对象和所有其他答案。因此,如果有人想带来类似以下JSON的内容,请尝试下面的JS代码。

{
    name  : 'value',
    name1 : { key1 : 'value1' },
    name2 : { key2 : 'value2' },
    name3 : { key2 : 'value2' }
}

$.fn.getForm2obj=函数(){var_={};$.map(this.serializeArray(),函数(n){常量键=n.name.match(/[a-zA-Z0-9_]+|(?=\[\])/g);如果(按键长度>1){让tmp=_;pop=keys.pop();for(设i=0;i<keys.length,j=keys[i];i++){tmp[j]=(!tmp[j]?(pop=='')?[]:{}:tmp[j]),tmp=tmp[j];}如果(pop=='')tmp=(!Array.isArray(tmp)?[]:tmp)、tmp.push(n.value);否则tmp[pop]=n.value;}else_[keys.pop()]=n.value;});返回_;}console.log($('form').getForm2obj());$('form input').change(函数(){console.clear();console.log($('form').getForm2obj());});<script src=“https://code.jquery.com/jquery-3.2.1.min.js“></script><表单><input name=“name”value=“value”><input type=“checkbox”name=“name1[]”value=“1”checked=“checked”>1<input type=“checkbox”name=“name1[]”value=“2”>2<input-type=“checkbox”name=“name1[]”value=“3”>3<br><input-type=“radio”name=“gender”value=“male”checked=“checked”>男性<input-type=“radio”name=“gender”value=“female”>女性<input name=“name2[key1]”value=“value1”><input name=“一个[另一个][另一个]”value=“value4”><input name=“name3[1][name]”value=“value4”><input name=“name3[2][name]”value=“value4”><input name=“[]”value=“value5”></form>