1、jquery扩展方法(表单数据格式化为json对象)
<script type="text/javascript"> // 将表单数据序列化为一个json对象,例如 {"name":"zs", "age":10} // 使用:var jsonObj = $("#formId").serializeObject(); $.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; }; </script>
2、jquery的表单序列化方法
(1)$("#formId").serialize(): 将所有表单选中项拼接成形如"username=zs&password=123"的字符串
(2)$("#formId").serializeArray(): 将表单所有选中项拼成json数组,格式为:
[{name: "username", value: "zs"},{name: "password", value: "123"}]
(3)$.param(jsonObj): 将json对象转换成形如"username=zs&password=123"的字符串
3、案例
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script src="http://code.jquery.com/jquery-1.12.4.min.js"></script> </head> <body> <h2>a页面</h2> <form id="form"> <input type="text" name="username"/> <input type="text" name="password"/> <input type="button" value="submit" onclick="formSubmit()"/> </form> </body> <script type="text/javascript"> function formSubmit() { var str = $("#form").serialize(); console.log(str); var jsonArray = $("#form").serializeArray(); console.log(jsonArray); console.log(jsonArray[0].name); console.log(jsonArray[0].value); console.log(jsonArray[1].name); console.log(jsonArray[1].value); var jsonObj = $("#form").serializeObject(); console.log(jsonObj); console.log(jsonObj.username + "---" + jsonObj.password);
var str = $.param(jsonObj);
console.log(str); } </script> <script type="text/javascript"> // 将表单数据序列化为一个json对象,例如 {"name":"zs", "age":10} // 使用:var jsonObj = $("#formId").serializeObject(); $.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; }; </script> </html>
结果: