需要被序列化的表单内容如下所示:
<form id="myForm">
用户名:<input type="text" name="username"/>
<br/>
年龄:<input type="text" name="age"/>
<br/>
爱好:
<input type="checkbox" name="hobby" value="篮球"/> 篮球
<input type="checkbox" name="hobby" value="乒乓球"> 乒乓球
<input type="checkbox" name="hobby" value="足球"> 足球
</form>
<input type="button" id="formBtn" value="发送">
序列化转 JSON
<script>
(function ($) {
$.fn.serializeJson = function () {
let serializeObj = {};
let array = this.serializeArray();
let str = this.serialize();
$(array).each(function () {
if (serializeObj[this.name]) {
if ($.isArray(serializeObj[this.name])) {
serializeObj[this.name].push(this.value);
} else {
serializeObj[this.name] = [serializeObj[this.name], this.value];
}
} else {
serializeObj[this.name] = this.value;
}
});
return serializeObj;
};
})(jQuery);
</script>