https://github.com/marioizquierdo/jquery.serializeJSON
效果图
加载使用
<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery.serializejson.js"></script>
form表单页面代码
<form id="formDemo" class="layui-form"> <table class="layui-table" lay-even> <colgroup> <col width="100"> <col width="200"> <col> </colgroup> <tbody> <tr> <th>用户名</th> <td id="userName"> <div class="layui-form-item layui-input-inline"> <input tyep="text" name="userName" class="layui-input"> </div> </td> </tr> <tr> <th>登录密码</th> <td id="password"> <div class="layui-form-item layui-input-inline"> <input tyep="text" name="password" class="layui-input"> </div> </td> </tr> <tr> <th>用户权限</th> <td id="role"> <div class="layui-form-item layui-input-inline"> <input type="text" name="role" class="layui-input" readOnly="true" value="管理员"> </div> </td> </tr> <tr> <th>手机号</th> <td id="phone"> <div class="layui-form-item layui-input-inline"> <input tyep="text" name="phone" class="layui-input"> </div> </td> </tr> <tr> <th>用户备注</th> <td id="nickName"> <div class="layui-form-item layui-input-inline"> <input tyep="text" name="nickName" class="layui-input"> </div> </td> </tr> </tbody> </table> </form>
序列化
<script type="text/javascript"> function getUser(){ console.log($(‘#formDemo‘).serializeJSON()); console.log(JSON.stringify($(‘#formDemo‘).serializeJSON())); return JSON.stringify($(‘#formDemo‘).serializeJSON()); } </script>
$(‘#formDemo‘).serializeJSON()返回的是一个Object体
{userName: "test", password: "test", role: "管理员", phone: "18888888866", nickName: "测试"}
JSON.stringify($(‘#formDemo‘).serializeJSON())返回的是JSON字符串
{"userName":"test","password":"test","role":"管理员","phone":"18888888866","nickName":"测试"}
使用Ajax传递给后台使用@RequestBody进行接收
<script type="text/javascript"> function addUser(){ var data = getUser(); $.ajax({ type: "POST", url: "${ctx}/auth/user/create", data: data, dataType: "json", contentType:"application/json", success: function(data){ alert(data.message); if(data.code==0){ layer.closeAll(); window.location.href="${ctx}/auth/users"; } } }); } </script>
若要在JS中获取键值对中的值可以进行如下处理
<script type="text/javascript"> var data = getUser(); var obj = eval("("+data+")"); alert(obj.userName); </script>
时间: 2024-11-05 14:48:00