jsp代碼
<script type="text/javascript"> $(function() { initProvinces(); }); /** * 獲取省列表 */ function initProvinces() { $('#province').empty(); $.ajax({ type : "POST", url : basePath + "district/getProvinces.do", success : function(data) { $.each(data, function(i, it) { $("<option value='" + it.id + "' />" + it.name + "<br>").click(function() { initCities(it.id); }).appendTo($('#province')); }); } }); } /** * 獲取市列表 */ function initCities(provinceID) { $('#city').empty(); $.ajax({ type : "POST", url : basePath + "district/getCities.do?province=" + provinceID, success : function(data) { $.each(data, function(i, it) { $("<option value='" + it.id + "' />" + it.name + "<br>").click(function() { initCounties(it.id); }).appendTo($('#province')); }); } }); } /** * 獲取區縣列表 */ function initCounties(cityID) { $('#county').empty(); $.ajax({ type : "POST", url : basePath + "district/getCounties.do?city=" + cityID, success : function(data) { $.each(data, function(i, it) { $("<option value='" + it.id + "' />" + it.name + "<br>") .appendTo($('#province')); }); } }); } //…… </script> <body> 選擇地區: <select id='province'><option>---省---</option></select> <select id='city'><option>---市---</option></select> <select id='county'><option>---區---</option></select> </body> spring MVC 代碼: @Controller @RequestMapping(value = "/district") public class districtController { @Resource private DistrictService districtService; /** * 獲取省列表 * @return * @throws Exception */ @RequestMapping(value = "getProvinces") @ResponseBody public Object getProvinces() throws Exception { return districtService.getProvinces(); } /** * 獲取市列表 * @param province * @return * @throws Exception */ @RequestMapping(value = "getCities") @ResponseBody public Object getCities(@RequestParam(value = "province") String province) throws Exception { return districtService.getCities(); } // 再往下級的獲取方式和getCities方法都相同,所以此處略過 }
3個select。 第一個select的option是寫到頁面的或者jsp標簽。然后給這個select的change綁定事件,讓這個事件去加載第二個select的option。同樣,給第二個select也綁定一個change事件去加載第三個select的數據。
//綁定事件 $("#select1").live(change,function(){ $.ajax({ url:aaaa,//提交的地址 data:{ select1id:$("#select1").val(); } type:'post', datatype:'json', success:function(return){ $("#select2 option").remove();//清空原來的選項 for(var i=0;i<return.length;i++) { $("#select2").append("<option val='"+return[i].value+"'> "+return[i].name+"</option>") } } }) })
@requestMapping("/") @responseBody public List<City> getCitysByErea(String ereaid,HttpServletRequest request,HttpServletResponse response){ List<City> citys =cityService.getXXX(erarid); return citys; }