首先实现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");
//获取部门ID
String 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;
}效果图
本文介绍了如何利用jQuery AJAX技术实现二级联动效果。首先展示所有部门,并在选择部门后,通过AJAX发送请求获取对应部门的班级信息。通过监听下拉框的点击事件,获取部门ID,再调用后台接口查询并更新班级列表。

241

被折叠的 条评论
为什么被折叠?



