前端頁面代碼
<tr>
<td width="106" height="28" align="right" class="hei"> 鄉(鎮):</td>
<td valign="middle" class="p_l">
<a href="#" class="textbox-icon combo-arrow" icon-index="0" tabindex="-1"
style="width: 18px; height: 20px;"></a>
<span></span>
<select id="street" lay-filter="selectTheme" name="street">
<option value="p_l"></option>
<option cclass="textbox combo" style="width: 100px; height: 20px;"
th:each="practice:${practices}"
th:value="${practice.name}" th:text="${practice.name}"
th:if="${practice.pid eq 0}"></option>
</select>
</tr>
<tr>
<td width="106" height="28" align="right" class="hei">村:</td>
<td valign="middle" class="p_l">
<span class="textbox combo" style="width: 118px; height: 20px;">
<span class="textbox-addon textbox-addon-right" style="right: 0px;">
<p class="textbox-icon combo-arrow" icon-index="0" tabindex="-1"
style="width: 18px; height: 20px;"></p>
</span><select id="community" name="community" class="textbox-text validatebox-text textbox-prompt">
</select>
</span>
</tr>
js代碼
<script src="layui/layui.js"></script>
<script type="text/javascript" >
layui.use(['form'], function() {
var $ = layui.$;
var form = layui.form;
form.on('select(selectTheme)', function (data) {//對應lay-filter="selectTheme"
var index1 = $('#street 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;
console.log(data);
var selectObj = document.getElementById("community");//對應id="theme"
selectObj.options.length = 0;
for (var i = 0; i < data.length; i++) {
selectObj.add(new Option(optionJson[i].name, optionJson[i].id));//對應數據庫中名字,兩個參數是(文本,value)
}
form.render();
}
})
});
})
</script>
Controller
/**
* js級聯
* author:嚴天賀
*/
@RequestMapping( "selectTheme")
@ResponseBody
public List<Practice> selectCollege(HttpServletRequest request) {
String board = request.getParameter("bo");//得到value值
QueryWrapper<Practice> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("name",board);
Practice practice=practiceService.getOne(queryWrapper);
Long id=practice.getId();
QueryWrapper<Practice> queryWrapper1=new QueryWrapper<>();
queryWrapper1.eq("pid",id);
List<Practice> practices = practiceService.list(queryWrapper1);//在數據庫查詢
return practices;
}
這裏尤其要注意@ResponseBody這個註解不能少