<body>
        <form action="#" method="post" id="form1">
            <input type="text" name="username" value="zhangxueliang"/>
            <input type="text" name="password" value="123456"/>
            <input type="checkbox" name="hobby" value="eat" checked="checked"/>
            <input type="checkbox" name="hobby" value="drink" checked="checked"/>
            <input type="checkbox" name="hobby" value="play" checked="checked"/>
        </form>
    </body>
    <script src="js/jquery-1.8.3.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
        $.fn.extend({
            serializeJson:function(){
                var json={};
                var msg = this.serializeArray();
                $(msg).each(function(){
                    if(json[this.name]){//如果name已存在
                        if(!json[this.name].push){//能push代表是数组
                            //不是数组
                            json[this.name]=[json[this.name]];
                        }
                        json[this.name].push(this.value||"");//装入数组
                    }else{
                        json[this.name]=this.value||"";
                    }
                });
                return json;
            }
        });
        
        $(function(){
            var formData = $("#form1").serializeJson();
            console.info(formData);
        })
    </script>

将表单数据转换为json代码分享_javascript