是否有一种简单的单行方式来获取表单的数据,就像以经典的仅html方式提交表单一样?

例如:

<form>
    <input type="radio" name="foo" value="1" checked="checked" />
    <input type="radio" name="foo" value="0" />
    <input name="bar" value="xxx" />
    <select name="this">
        <option value="hi" selected="selected">Hi</option>
        <option value="ho">Ho</option>
</form>

输出:

{
    "foo": "1",
    "bar": "xxx",
    "this": "hi"
}

像这样的东西太简单了,因为它没有(正确地)包括文本区域,选择,单选按钮和复选框:

$("#form input").each(function () {
    data[theFieldName] = theFieldValue;
});

当前回答

var formData = new FormData($('#form-id'));
params   = $('#form-id').serializeArray();

$.each(params, function(i, val) {
    formData.append(val.name, val.value);
});

其他回答

这将把所有表单字段附加到JavaScript对象“res”:

var res = {};
$("#form input, #form select, #form textarea").each(function(i, obj) {
    res[obj.name] = $(obj).val();
})

对于那些更喜欢Object而不是序列化字符串的人(比如$(form).serialize()返回的字符串,以及对$(form).serializeArray()的稍微改进),请随意使用下面的代码:

var Form = {
    _form: null,
    _validate: function(){
        if(!this._form || this._form.tagName.toLowerCase() !== "form") return false;
        if(!this._form.elements.length) return false;
        return true;
    }, _loopFields: function(callback){
        var elements = this._form.elements;
        for(var i = 0; i < elements.length; i++){
            var element = form.elements[i];
            if(name !== ""){
                callback(this._valueOfField(element));
            }
        }
    }, _valueOfField: function(element){
        var type = element.type;
        var name = element.name.trim();
        var nodeName = element.nodeName.toLowerCase();
        switch(nodeName){
            case "input":
                if(type === "radio" || type === "checkbox"){
                    if(element.checked){
                        return element.value;
                    }
                }
                return element.value;
                break;
            case "select":
                if(type === "select-multiple"){
                    for(var i = 0; i < element.options.length; i++){
                        if(options[i].selected){
                            return element.value;
                        }
                    }
                }
                return element.value;
                break;
            case "button":
                switch(type){
                    case "reset": 
                    case "submit": 
                    case "button":
                        return element.value;
                        break;
                }
                break;
        } 
    }, serialize: function(form){
        var data = {};
        this._form = form;

        if(this._validate()){
            this._loopFields(function(value){
                if(value !== null) data[name] = value;
            });
        }
        return data;
    }
};

要执行它,只需使用form .serialize(form),函数将返回一个类似于下面的对象:

<!-- { username: "username", password: "password" } !-->
<input type="text" value="username">
<input type="password" value="password">

作为奖励,这意味着您不必为了一个序列化函数而安装整个jQuery包。

使用$('form').serializeArray(),它返回一个数组:

[
  {"name":"foo","value":"1"},
  {"name":"bar","value":"xxx"},
  {"name":"this","value":"hi"}
]

另一个选项是$('form').serialize(),它返回一个字符串:

"foo=1&bar=xxx&this=hi"

看看这个jsfiddle演示

$( "form" ).bind( "submit", function(e) { e.preventDefault(); console.log( $(this).serializeObject() ); //console.log( $(this).serialize() ); //console.log( $(this).serializeArray() ); }); $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each( a, function() { if ( o[this.name] !== undefined) { if ( ! o[this.name].push ) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }; <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <form> <input type="radio" name="foo" value="1" checked="checked" /> <input type="radio" name="foo" value="0" /> <input name="bar" value="xxx" /> <select name="this"> <option value="hi" selected="selected">Hi</option> <option value="ho">Ho</option> </select> <input type="submit" value="Submit" /> </form>

Codepen

document.querySelector('form').addEventListener('submit', (e) => {
  const formData = new FormData(e.target);
  // Now you can use formData.get('foo'), for example.
  // Don't forget e.preventDefault() if you want to stop normal form .submission
});

这是一个吹毛求疵的答案,但让我解释为什么这是一个更好的解决方案:

We're properly handling a form submit rather than a button press. Some people like to push enter on fields. Some people use alternative input devices such as speech input or other accessibility devices. Handle the form submit and you correctly solve it for everyone. We're digging into the form data for the actual form that was submitted. If you change your form selector later, you don't have to change the selectors for all the fields. Furthermore, you might have several forms with the same input names. No need to disambiguate with excessive IDs and what not, just track the inputs based on the form that was submitted. This also enables you to use a single event handler for multiple forms if that is appropriate for your situation. The FormData interface is fairly new, but is well supported by browsers. It's a great way to build that data collection to get the real values of what's in the form. Without it, you're going to have to loop through all the elements (such as with form.elements) and figure out what's checked, what isn't, what the values are, etc. Totally possible if you need old browser support, but the FormData interface is simpler. I'm using ES6 here... not a requirement by any means, so change it back to be ES5 compatible if you need old browser support.