zoukankan      html  css  js  c++  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='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");
    	  });
      }
    

      

  • 相关阅读:
    作业信息获取
    SQL Server数据库性能监控计数器
    c# 索引器學習
    C# DataGridView 小技巧
    C# DataTable 小技巧
    c# 小技巧
    C# new,Virtual,abstract,sealed,Override的簡單理解
    C# 位操作符
    C# 類型小技巧
    C# partial 局部类型
  • 原文地址:https://www.cnblogs.com/lt123/p/7208926.html
Copyright © 2011-2022 走看看