1. 程式人生 > >jQuery實現form表單序列化轉換為json對象功能示例

jQuery實現form表單序列化轉換為json對象功能示例

bubuko ret FN RR inpu info images serialize orm

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>jquery form序列化轉換為json對象</title>
    <script src="//cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script>
    </script>
  </head>
  <body>
    <form action="" name="post_form
" id="post_form"> 姓名:<input type="name" name="name" value=""> <br/>性別:<input type="radio" name="sex" value="" checked>男<input type="radio" name="sex" value=""><br/>愛好:<input type="checkbox" name="loves" value="籃球" >籃球<input type="checkbox
" name="loves" value="足球">足球 <br/>籍貫:<select name="province"> <option value="上海">上海</option> <option value="北京">北京</option> <option value="深圳">深圳</option> </select> </form> <div id="
result" style="margin-top:20px;width:600px;height:100px;border:1px solid #f00;"> </div> <div> <button id="send">發送</button> </div> <script> //jquery form序列化轉換為json對象 (function($){ $.fn.serializeJson=function(){ var serializeObj={}; var array=this.serializeArray(); var 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); $(document).ready(function(){ $("#send").click(function(){ var post_data=$("#post_form").serializeJson();//表單序列化 $("#result").html(JSON.stringify(post_data)); }) }) </script> </body> </html>

運行結果:

技術分享圖片

技術分享圖片

jQuery實現form表單序列化轉換為json對象功能示例