在使用jquery框架开发项目时,使用ajax提交数据经常会使用Jquery序列化提交函数serialize,然而在遇到选中checkbox会提交checkbox的默认值“on”,不选中则不会提交checkbox 的name字段。如下图所示,我想要提交一些个人信息,如果在爱好这一栏我什么都不选则序列化函数什么都不会提交,这将会影响我们更新数据。
而我们想要的效果是我选中时值为“true“,不选中时为“false“,下面介绍一种重写serialize函数,以提交数据达到想要的效果。说一下大致的思路:
1.首先需要重写这个函数,使用jquery的重写函数声明方式$.fn.serializeObject;
2.定义一个空对象o,用于存放我们接下来要遍历的数据;
3.定义一个对象a,是序列化后的表单元素;
4.遍历对象a,将name属性存放于对象o,并将值赋给相应的name属性,遇到重复的name属性,使用嵌套数组的形式保存;
5.遍历表单中的checkbox ,如果对象o中没有这个属性,则添加到o对象中,并赋值为false,如果有这个属性,则将值更该为true;
6.返回对象。
测试代码如下所示。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>序列化表单</title>
<script type="text/javascript" src="jquery-3.2.0.js"></script>
<script type="text/javascript">
$(function(){
$.fn.serializeObject=function(){
var o={};
var a=this.serializeArray();//序列化整个表单
$.each(a,function(){//遍历a对象
//如果o对象中已经有重复的属性,则需要嵌套数组重复插入
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||'';
}
});
var $checkbox=$('input[type=checkbox]',this);
$.each($checkbox,function(){
if(!o.hasOwnProperty(this.name)){
o[this.name]='false';
}
else{
o[this.name]='true';
}
});
return o;
}
$("#submit").click(function(){
console.log($("#testForm").serializeObject());
})
})
</script>
</head>
<body>
<form id="testForm">
<div>姓名:<input type="text" name="name"></div>
<div>年龄:<input type="text" name="age"></div>
<div>职业:<input type="text" name="job"></div>
<div>请选择爱好:</div>
<div>
篮球:<input type="checkbox" name="basket">
足球:<input type="checkbox" name="baseball">
乒乓球:<input type="checkbox" name="pingpang">
</div>
<div>
是否在职:
<input type="radio" name="state" value="true">是
<input type="radio" name="state" value="false">否
</div>
<div>
<input type="button" name="" id="submit" value="提交"/>
</div>
</form>
</body>
</html>