首页 > Web开发 > 详细

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

时间:2019-01-01 20:28:01      阅读:135      评论:0      收藏:0      [点我收藏+]
<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代码分享

原文:https://www.cnblogs.com/niwotaxuexiba/p/10205753.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!