首先實現jquery ajax的二級聯動 要下載個jquery.js 我在這裡就不準備了 自行百度下載
背景介紹:通過部門的ID來尋找部門下的所有班級
我實現二級聯動的思路是:先查詢所有部門 顯示在頁面上 如圖 :
其次在使用下拉框的點擊事件 擷取到部門的ID ,然後通過部門的ID 進行尋找班級。
貼代碼
前台JSP:
<select id="department" name="departmentId" onChange="findClass()"><option value="0">請選擇</option><c:forEach items="${departmentAll}" var="d"><option value="${d.departmentId}">${d.departmentName}</option></c:forEach></select><select id="classId" name="classId" ><option value="0">請選擇</option></select>
ajax:
function findClass(){var departmentId = $("#department").attr("value");$.ajax({url:"${pageContext.request.contextPath}/student/findClass",type:"get",timeout:"1000",data:{departmentId:departmentId},success:function(data){$("#classId option").remove();$("#classId").append("<option value='0'>請選擇</option>");if (data != 0) {for ( var i = 0; i < data.length; i++) {var classId = data[i].classId;var className = data[i].className;$("#classId").append("<option value="+classId+">"+ className + "</option>");}}},error : function(XMLResponse) {alert(XMLResponse.responseText);}});}
這是後台controller的代碼:
查詢部門:
ModelAndView modelAndView=new ModelAndView();List<Department> departmentAll = departmentService.findDepartmentAll();modelAndView.setViewName("student/add");modelAndView.addObject("departmentAll", departmentAll);return modelAndView;
查詢班級:
@RequestMapping(value="findClass")public String findClass(HttpServletRequest reuqest,HttpServletResponse response) throws Exception{response.setContentType("text/json; charset=UTF-8");//擷取部門IDString departmentId = reuqest.getParameter("departmentId");Integer id = Integer.parseInt(departmentId);PrintWriter out = null;try{out = response.getWriter();}catch(Exception e){e.printStackTrace();}JSONArray array = new JSONArray();JSONObject member = null;try{//根據部門的Id 來尋找部門下的所有班級List<Classes> ClassesList = classesService.findClassByDepartmentId(id);for(Classes classes:ClassesList){member = new JSONObject();member.put("classId", classes.getClassId());member.put("className", classes.getClassName());array.put(member);}}catch(Exception e){e.printStackTrace();}out.print(array.toString());return null;}
效果圖