是否有一种简单的单行方式来获取表单的数据,就像以经典的仅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;
});

当前回答

我编写了一个库来解决这个问题:JSONForms。它采用一个表单,遍历每个输入并构建一个易于阅读的JSON对象。

假设你有以下表单:

<form enctype='application/json'>
  <input name='places[0][city]' value='New York City'>
  <input type='number' name='places[0][population]' value='8175133'>
  <input name='places[1][city]' value='Los Angeles'>
  <input type='number' name='places[1][population]' value='3792621'>
  <input name='places[2][city]' value='Chicago'>
  <input type='number' name='places[2][population]' value='2695598'>
</form>

将表单传递给JSONForms的encode方法将返回以下对象:

{
  "places": [
    {
      "city": "New York City",
      "population": 8175133
    },
    {
      "city": "Los Angeles",
      "population": 3792621
    },
    {
      "city": "Chicago",
      "population": 2695598
    }
  ]
}

下面是表单的演示。

其他回答

你也可以使用FormData对象;FormData对象允许您编译一组键/值对,以便使用XMLHttpRequest发送。它主要用于发送表单数据,但也可以独立于表单用于传输键控数据。

        var formElement = document.getElementById("myform_id");
        var formData = new FormData(formElement);
        console.log(formData);
$("#form input, #form select, #form textarea").each(function() {
 data[theFieldName] = theFieldValue;
});

除此之外,你可能想看看serialize();

我有点惊讶,因为下面没有人提到解决方案。

通过document.forms.namedItem函数获取表单数据

var form = document.forms.namedItem("fileinfo");

form.addEventListener('submit', function(ev) {
   var oData = new FormData(form);
}

HT的

<form name="fileinfo">
  <label>Your email address:</label>
  <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
  <label>Custom file label:</label>
  <input type="text" name="filelabel" size="12" maxlength="32" /><br />
  <label>File to stash:</label>
  <input type="file" name="file" required />
  <input type="submit" value="Stash the file!" />
</form>
<div></div>

我已经包括答案,也给回所需的对象。

function getFormData(form) {
var rawJson = form.serializeArray();
var model = {};

$.map(rawJson, function (n, i) {
    model[n['name']] = n['value'];
});

return model;
}

这是我的香草JS版本(在Chrome上测试)

适用于:

name = "输入" Name ="form[Name]"(创建一个对象) Name ="checkbox[]"(创建一个数组对象) Name ="form[checkbox][]"(创建一个数组) Name ="form[select][Name]"(创建一个只包含所选值的对象)

/**
 * Get the values from a form
 * @param formId ( ID without the # )
 * @returns {object}
 */
function getFormValues( formId )
{
    let postData = {};
    let form = document.forms[formId];
    let formData = new FormData( form );

    for ( const value of formData.entries() )
    {
        let container = postData;
        let key = value[0];
        let arrayKeys = key.match( /\[[\w\-]*\]/g ); // Check for any arrays

        if ( arrayKeys !== null )
        {
            arrayKeys.unshift( key.substr( 0, key.search( /\[/ ) ) );  // prepend the first key to the list
            for ( let i = 0, count = arrayKeys.length, lastRun = count - 1; i < count; i++ )
            {
                let _key = arrayKeys[i];
                _key = _key.replace( "[", '' ).replace( "]", '' ); // Remove the brackets []
                if ( _key === '' )
                {
                    if ( ! Array.isArray( container ) )
                    {
                        container = [];
                    }

                    _key = container.length;
                }

                if ( ! (_key in container) ) // Create an object for the key if it doesn't exist
                {
                    if ( i !== lastRun && arrayKeys[i + 1] === '[]' )
                    {
                        container[_key] = [];
                    }
                    else
                    {
                        container[_key] = {};
                    }
                }

                if ( i !== lastRun ) // Until we're the last item, swap container with it's child
                {
                    container = container[_key];
                }

                key = _key;
            }
        }
        container[key] = value[1]; // finally assign the value
    }

    return postData;
}