How can I get form data with JavaScript/jQuery?
Is there a simple, one-line way to get the data of a form as it would be if it was to be submitted in the classic HTML-only way?
For example, in:
<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>
Out:
{
"foo": "1",
"bar": "xxx",
"this": "hi"
}
Something like this is too simple, since it does not (correctly) include textareas, selects, radio buttons and checkboxes:
$("#form input").each(function() {
data[theFieldName] = theFieldValue;
});
$('form').serialize() //this produces: "foo=1&bar=xxx&this=hi"
演示
Use $('form').serializeArray()
, which returns an array :
[
{"name":"foo","value":"1"},
{"name":"bar","value":"xxx"},
{"name":"this","value":"hi"}
]
Other option is $('form').serialize()
, which returns a string :
"foo=1&bar=xxx&this=hi"
Take a look at this jsfiddle demo
基于jQuery.serializeArray
,返回键值对。
var data = $('#form').serializeArray().reduce(function(obj, item) {
obj[item.name] = item.value;
return obj;
}, {});
链接地址: http://www.djcxy.com/p/26420.html