参考了官网的用法
1.加入jar包 bootstrap-switch.min.js和bootstrap-switch.min.css
2.所在的jsp页面引入以上两个文件
<link href="${pageContext.request.contextPath}/static/css/bootstrap-switch.min.css" rel="stylesheet">
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/bootstrap-switch.min.js"></script>
3.页面是表格形式的,该按钮用在最后一列,每一行是一个对象,页面数据是用list循环输出;
<tbody>
<tr class="back">
<td width="4%">序号</td>
<td width="20%">学校编号</td>
<td width="40%">学校名称</td>
<td width="36%">填报设置</td>
</tr>
<c:forEach var="school" items="${list}" varStatus="status">
<tr>
<td>${status.index+1}</td>
<td id="code">${school.schoolCode}</td>
<td>${school.schoolName}</td>
<td><input name="switchinput" value="${school.switchValue}" type="checkbox" schValue="${school.id}" <c:if test="${school.switchValue eq 1}">checked</c:if>></td>
</tr>
</c:forEach>
</tbody>
4.js里面初始化的写法:
$().ready(function () {
$('input[name="switchinput"]').bootstrapSwitch({ onText:"启动",
offText:"停止",
onColor:"success",
offColor:"primary",
size:"small",
onSwitchChange:function(event,state){
if(state==true){
$(this).val("1");
}else{
$(this).val("0");
}
}
});
})
5.重点
function save(){
var schArr = new Array();
$("input[name='switchinput'][value='1']").each(function(){
schArr.push($(this).attr("schValue")); // 开关按钮值为1的对象存储在数组里
})
$.ajax({
type : 'post',
async : false,
url : '${pageContext.request.contextPath}/info/schoolSwitchSet/base/process',
dataType: 'json',
data : {ids:schArr},
success : function(data) {
if (data.success){ alert('设置成功');
}
else alert(data.msg);
}
})
}
6.后台逻辑代码:
@RequestMapping(value = "base/process", method = RequestMethod.POST)
@ResponseBody
public AjaxResult baseProcess(@RequestParam(value="ids[]", required=false) List<Long> ids) {
try{
// 可以得到ids数组
......................................
}
catch(Exception e){
//
logger.error(e.getMessage(), e);
return AjaxResult.fail("服务器发生错误,请稍后重试");}
}