是否有一种简单的单行方式来获取表单的数据,就像以经典的仅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;
});
使用$('form').serializeArray(),它返回一个数组:
[
{"name":"foo","value":"1"},
{"name":"bar","value":"xxx"},
{"name":"this","value":"hi"}
]
另一个选项是$('form').serialize(),它返回一个字符串:
"foo=1&bar=xxx&this=hi"
看看这个jsfiddle演示
我编写了一个库来解决这个问题: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
}
]
}
下面是表单的演示。