jQuery序列化表单为JSON对象

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

    <form id="myform">  
        <table>  
            <tr>  
                <td>姓名:</td>  
                <td> <input type="text" name="name" /> </td>  
            </tr>  
            <tr>  
                <td>性别:</td>  
                <td>  
                    <input type="radio" name="sex" value="1"> 男  
                    <input type="radio" name="sex" value="0"> 女  
                </td>  
            </tr>  
            <tr>  
                <td>年龄:</td>  
                <td>  
                    <select name="age">  
                        <option value="20">20</option>  
                        <option value="21">21</option>  
                        <option value="22">22</option>  
                    </select>  
                </td>  
            </tr>  
            <tr>  
                <td>爱好</td>  
                <td>  
                    <input type="checkbox" value="basketball" name="hobby">篮球  
                    <input type="checkbox" value="volleyball" name="hobby">排球  
                    <input type="checkbox" value="football" name="hobby">足球  
                    <input type="checkbox" value="earth" name="hobby">地球  
                </td>  
            </tr>  
            <tr>  
                <td colspan="2">  
                    <input type="button" id="ajaxBtn" value="提交" />  
                </td>  
            </tr>  
        </table>  
    </form>  

    <script type="text/javascript">  
          
        $(function() {  
            $("#ajaxBtn").click(function() {  
                    var params = $("#myform").serializeObject(); //将表单序列化为JSON对象   
                    console.info(params);  
                })  
        })  
      
        $.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>