用表單格式化外掛jquery.serializejson將表單上的資料轉換成JSON物件
阿新 • • 發佈:2019-01-31
沒有這個外掛之前要想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等標籤也是適用的