首页 > 代码库 > java 异步实现省市联动

java 异步实现省市联动

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=http://www.mamicode.com/‘ProvinceCityServlet‘/>",{"method":"findProvinces"},function(data){
//另一种遍历方式  还有each方式遍历 但在这里不常用   常用在遍历jquery元素集合上
	for(var i = 0; i < data.length; i++){
	  $("#provinceSelect").append("<option value=http://www.mamicode.com/‘"+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=http://www.mamicode.com/‘ProvinceCityServlet‘/>",{"method":"findCitysbyPid","pId":pId},function(data){
			  for(var key in data)
			  {
			  		$("#citySelect").append("<option>"+data[key].name+"</option>");
			  }
			  
		  },"json");
	  });
  }

  

java 异步实现省市联动