二级联动 网上搜了好久都没看懂,终于看懂了一个:Springboot+Mybatis+Jquery实现自定义二级联动。将它改了下改成了layui的。
html代码
<div class="layui-col-xs2 layui-input-inline">
<form class="layui-form layui-form-pane">
<select lay-filter="selectTheme" id="board" selected="selected"><!--一级-->
<option value="" selected=""></option>
<option th:each="b:${board}" th:text="${b.boName}" th:value="${b.boId}"></option>
</select>
</form>
</div>
<div class="layui-col-xs1 layui-input-inline">
<form class="layui-form layui-form-pane" action="">
<select id="theme"><!--二级-->
</select>
</form>
</div>
上面比较重要的是lay-filter=“selectTheme”(代替onchange来响应),id=“board”,id=“theme”。
js代码
layui.use(['form'], function() {
var $ = layui.$;
var form = layui.form;
form.on('select(selectTheme)', function (data) {//对应lay-filter="selectTheme"
var index1 = $('#board option:selected').val();//对应id="board" 得到一级菜单选中值的value
var optionJson = [];
$.ajax({
url: "/selectTheme",//对应controller层
type: "post",
data: {"bo": index1},//将选中值的value传给controller
datatype: "json",
success: function (data) {
optionJson = data;
var selectObj = document.getElementById("theme");//对应id="theme"
selectObj.options.length = 0;
for (var i = 0; i < data.length; i++) {
selectObj.add(new Option(optionJson[i].thName, optionJson[i].thId));//对应数据库中名字,两个参数是(文本,value)
}
form.render();
}
})
});
})
controller
@Autowired
private IBoardService bs;
@Autowired
private IThemeService ts;
@RequestMapping("/index")
public String index(Model model){
List<Board> board=bs.selectAllBoard();
model.addAttribute("board",board);
return "index";
}
@RequestMapping(value = "/selectTheme", method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public List<Theme> selectCollege(HttpServletRequest request){
String board=request.getParameter("bo");//得到value值
System.out.println(board);
List<Theme> theme=ts.selectTheme(Integer.valueOf(board));//在数据库查询
return theme;
}
IBoardService 与 IThemeService 就只是根据条件查询数据库