用表单格式化插件jquery.serializejson将表单上的数据转换成JSON对象

没有这个插件之前要想JS获取到form表单的数据,在ajax传到后台也是蛮痛苦的事,虽然都是简单用$(“#id”).val()获取到表单的值,要是量多了也是很磨人的。

好吧,废话不多说!看下这个jquery.serializejson.js插件是怎么给我们带来便利的
像正常使用jquery一样把下载好的文件引入到页面中
下载地址

<script src=/js/jquery.serializejson.js</script>

下面是简单的一个form表单的html,特别注意的是form表单的id一定要设值,后面有用

<form method="get" class="form-horizontal" id="rules">
                                <input type="hidden" name="id" id="id" value="${(integralSystem.id)!""}"/>
                                <div class="form-group">
                                    <label class="col-sm-2 col-sm-offset-2 control-label">用户活动</label>
                                    <div class="col-sm-4">
                                        <input type="text" name="userActions" id="userActions" class="form-control" readonly="readonly" value="${(integralSystem.userActions)!""}">
                                    </div>
                                </div>
                                <div class="hr-line-dashed"></div>

                                <#if (integralSystem.userActions)=='注册账号'>
                                <div class="form-group">
                                    <label class="col-sm-2 col-sm-offset-2 control-label">一次性获得积分</label>
                                    <div class="col-sm-4">
                                        <input type="text" name="points" id="points" class="form-control" placeholder="积分" value="${(rules.points)!""}">
                                    </div>
                                </div>
                                </#if>
                                <button class="btn btn-primary" type="button" onclick="getRules()">保存</button>
                                </from>

用一个button的onclick事件来获取整个表单的input值,转为json对象,只有一行代码就搞定。

 function getRules(){
     return JSON.stringify($('#rules').serializeJSON());
 }

后面我们想把form表单的所有值传到后台就不用一个一个写了,直接通过getRules()函数拿到整个JSON对象,后台也方便解析。

$.post("saveIntegralSystem.htm",{"rules":getRules()},function(data){
                 data=JSON.parse(data);
                 alertify.alert(data.message,function(){
                     if(data.success){
                         window.location.href='integralSystemIndex.htm';
                     }
                  });
              });

这里只展示了input标签,其他select等标签也是适用的

猜你喜欢

转载自blog.csdn.net/gavin_wangzg/article/details/79289469
今日推荐