1.
省份:<select id="provinceSelect"></select> 城市:<select id="citySelect"></select>
2.get,post请求都可
public String findProvinces(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Province> list=dao.findProvinces(); String jsonString=JSONArray.fromObject(list).toString(); response.getWriter().write(jsonString); return null; } public String findCitysbyPid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pId=request.getParameter("pId"); int provinceId=Integer.parseInt(pId); List<City> list=dao.findCitysByPId(provinceId); String jsonString=JSONArray.fromObject(list).toString(); response.getWriter().write(jsonString); return null; }
3.
function initProvinceSelect() { $.getJSON("<c:url value=‘ProvinceCityServlet‘/>",{"method":"findProvinces"},function(data){ //另一种遍历方式 还有each方式遍历 但在这里不常用 常用在遍历jquery元素集合上 for(var i = 0; i < data.length; i++){ $("#provinceSelect").append("<option value=‘"+data[i].pid+"‘>"+data[i].name+"</option>") } bindCitySelectChange();//注意绑定事件的顺序 总是放在依赖控件加载完后面 因为是异步加载 //初始化 很重要 一般是想不到的 $("#provinceSelect").change(); }); }
4.
function bindCitySelectChange() { $("#provinceSelect").change(function(){ var pId=$(this).val();//获取select选中项 很重要 $("#citySelect").empty(); //post get都行 $.post("<c:url value=‘ProvinceCityServlet‘/>",{"method":"findCitysbyPid","pId":pId},function(data){ for(var key in data) { $("#citySelect").append("<option>"+data[key].name+"</option>"); } },"json"); }); }
时间: 2024-11-06 13:14:18