您的位置:首页 > Web前端 > JQuery

使用 jQuery.form.serialize() 获取表单数据后转成 json

2018-01-24 16:45 961 查看
HTML:

<form action="#" method="post">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" id="email" />
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</div>
<p>
<input type="submit" value="Send" />
</p>
</form>

JavaScript:
(function ($) {
$.fn.serializeFormJSON = 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;
};
})(jQuery);

$('form').submit(function (e) {
e.preventDefault();
var data = $(this).serializeFormJSON();
console.log(data);

/* Object
email: "value"
name: "value"
password: "value"
*/
});

转载网址:https://jsfiddle.net/gabrieleromanato/bynaK/
如有侵权,请联系删除!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐