jQuery序列化表单为JSON对象
1.html
<form action="formGetData.html" method="get">
<p>First name: <input type="text" name="fname" /></p>
<p>Last name: <input type="text" name="lname" /></p>
<input type="button" id="submitBtn" value="提交" />
</form>
2.js
$('#submitBtn').click(function() {
var formData = $('form').serializeObject();
console.log(formData);
});
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if(o[this.name]) {
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;
}
效果: