jquery ajax 二級聯動

來源:互聯網
上載者:User

首先實現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;}

效果圖

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.