[html]
 view plain copy

 
  1. <form id=“myform”>  
  2.     <table>  
  3.         <tr>  
  4.             <td>姓名:</td>  
  5.             <td<input type=“text” name=“name” /> </td>  
  6.         </tr>  
  7.         <tr>  
  8.             <td>性别:</td>  
  9.             <td>  
  10.                 <input type=“radio” name=“sex” value=“1”> 男  
  11.                 <input type=“radio” name=“sex” value=“0”> 女  
  12.             </td>  
  13.         </tr>  
  14.         <tr>  
  15.             <td>年龄:</td>  
  16.             <td>  
  17.                 <select name=“age”>  
  18.                     <option value=“20”>20</option>  
  19.                     <option value=“21”>21</option>  
  20.                     <option value=“22”>22</option>  
  21.                 </select>  
  22.             </td>  
  23.         </tr>  
  24.         <tr>  
  25.             <td>爱好</td>  
  26.             <td>  
  27.                 <input type=“checkbox” value=“basketball” name=“hobby”>篮球  
  28.                 <input type=“checkbox” value=“volleyball” name=“hobby”>排球  
  29.                 <input type=“checkbox” value=“football” name=“hobby”>足球  
  30.                 <input type=“checkbox” value=“earth” name=“hobby”>地球  
  31.             </td>  
  32.         </tr>  
  33.         <tr>  
  34.             <td colspan=“2”>  
  35.                 <input type=“button” id=“ajaxBtn” value=“提交” />  
  36.             </td>  
  37.         </tr>  
  38.     </table>  
  39. </form>  
[javascript] view plain copy

 
  1. <script type=“text/javascript”>  
  2.       
  3.     $(function() {  
  4.         $(“#ajaxBtn”).click(function() {  
  5.                 var params = $(“#myform”).serializeObject(); //将表单序列化为JSON对象   
  6.                 console.info(params);  
  7.             })  
  8.     })  
  9.   
  10.     $.fn.serializeObject = function() {  
  11.         var o = {};  
  12.         var a = this.serializeArray();  
  13.         $.each(a, function() {  
  14.             if (o[this.name]) {  
  15.                 if (!o[this.name].push) {  
  16.                     o[this.name] = [ o[this.name] ];  
  17.                 }  
  18.                 o[this.name].push(this.value || \’\’);  
  19.             } else {  
  20.                 o[this.name] = this.value || \’\’;  
  21.             }  
  22.         });  
  23.         return o;  
  24.     }  
  25. </script>  

 

上述serializeObject方法是将form序列化为JSON对象

版权声明:本文为exmyth原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/exmyth/p/6947515.html