jQuery select三级联动
一:controller代码:
后台就简单返回map集合就行,表结构也是简单的通过父类Id来实现的
/** * 三级联动 * @param id 父类id * @return */ @RequestMapping(value = "/Options", method = { RequestMethod.POST, RequestMethod.GET}) @ResponseBody public List<Map<String, Object>> Options(int id){ List<Map<String, Object>> dataList=new ArrayList<Map<String,Object>>(); try { if(id!=null && id!=0){ List<Item> items=itemService.getAllName(id); for (Item i : items) { Map<String, Object> map=new HashMap<String, Object>(); map.put("id", i.getId()); map.put("name", i.getName()); dataList.add(map); } } } catch (Exception e) { e.printStackTrace(); } return dataList; }
二:前端代码(ajax实现页面无刷新):
$().ready(function() { $("#oneId").on("change",function(){ var oneId = $("#oneId").val(); $("#twoId").html("<option value='0'>--请选择--</option>"); $("#threeId").html("<option value='0'>--请选择--</option>"); $.ajax({ url: "Options.action", type: "POST", data: { itemCatId:oneId //一级类目id }, dataType: "json", success: function(data) { $.each(data, function(idx, obj) { $("#twoId").append("<option value='"+obj.id+"'>" + obj.name + "</option>"); }); } }); }); $("#twoId").change(function () { var twoId = $("#twoId").val(); $("#threeId").html("<option value='0'>--请选择--</option>"); $.ajax({ url: "Options.action", type: "POST", data: { itemCatId:twoId//二级类目id }, success: function(data) { $.each(data, function(idx, obj) { $("#threeId").append("<option value='"+obj.id+"'>" + obj.name+ "</option>"); }); } }); }); });
页面代码就不贴了,此三级联动是在绑定好一级分类的基础上进行的,oneId,twoId,threeId分别指一,二,三级select的id