学习了一下jQury序列化,分为两个方法,整理如下:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>测试</title> <script src="./jquery-1.8.1.min.js" type="text/javascript"></script> <script> $(function(){ $("#sendButton").click(function(){ //方法1 serialize()方法,该方法作用于一个jQuery对象,能够将DOM元素内容序列化成字符串 //该方法能够对中文进行编码处理,相应的需要进行解码处理 //该方法的核心是$.params()方法,用来将一个数组或者对象按照k/v进行序列化 var obj1 = $("#testForm").serialize(); console.log(decodeURIComponent(obj1,true)); //方法2 serializeArray()方法,将用作提交的表单元素的值编译成拥有name和value对象组成的数组。例如[ { name: a value: 1 }, { name: b value: 2 },...] var obj2 = $("#testForm").serializeArray(); console.log(obj2); }) }) </script> </head> <body> <form id="testForm" action="#"> <input name = "name" placeholder="姓名"/> <input name = "age" placeholder="年龄"/> <input name = "height" placeholder="身高"/> <input name = "hometown" placeholder="家乡"/> <input id="sendButton" type="button" value="click"></input> </form> </body> </html>
API中并没有提供直接序列化成json对象的方法,可以在现有方法的基础上,稍作修改即可:<script type="text/javascript"> $(function() { $("#sendButton").click(function() { var datas = $("#testForm").serializeJsonObj(); console.log(datas); }) }) $.fn.serializeJsonObj = function() { var result = {}; var temp = this.serializeArray(); $.each(temp, function() { if (result[this.name]) { if (!result[this.name].push) { result[this.name] = [ result[this.name] ]; } result[this.name].push(this.value || ''); } else { result[this.name] = this.value || ''; } }); return result; } </script>
转载于:https://www.cnblogs.com/xieshuang/p/6054272.html