JQuery Ajax三级联动地区上拉框

JQuery Ajax三级联动地区下拉框

JSP部分代码

 

<script src="/js/jquery-1.2.6.min.js" type="text/javascript"></script>
<script>
 //为了避免jquery中的'$'与其它的'$'冲突,在此将jquery中的'$'重命名为'jQuery'
 var jQuery=$;
</script>

 

<script>
  //初始化数据
  jQuery(document).ready(function(){
   getProvince();

 });
  
  //取所有省份
  function getProvince(){

   //&callback=?"注意这个是为了解决跨域访问的问题   
   var url ="<%=request.getContextPath() %>/getAreaJSON?areaId=0&callback=?";
   
   jQuery.getJSON(url,null,function call(result){  
         setProvince(result); 
     });
   
   //显示或隐藏激活卡
   jQuery("#actionCardChk").click(function(){
    if(jQuery("#actionCardChk").attr("checked")==true){
     jQuery("#actionCardDiv").show();
    }else{
     jQuery("#actionCardDiv").hide();
    }
   });
   
   //显示或隐藏新增常用地址
   jQuery("#addressChk").click(function(){
    if(jQuery("#addressChk").attr("checked")==true){
     jQuery("#addressDiv").show();
    }else{
     jQuery("#addressDiv").hide();
    }
   });

 }
  
  //设置省份
  function setProvince(result){
  
  var province = document.getElementById("toProvince");
  
  jQuery.each(result.data, function(i, area){
         var value = area.id;
    var text = area.name;
    var option = new Option(text,value);
    province.options.add(option);
         
    });  
  }
  
  //按上级ID取子地区
  function getArea(name){
   
   if( name=='city' ){
    clearSel(document.getElementById("toCity")); //清空城市
    var province = document.getElementById("toProvince");
    if(province.options[province.selectedIndex].value == "") return;
    var areaId = province.options[province.selectedIndex].value;
    
    var url ="<%=request.getContextPath() %>/getAreaJSON?areaId="+areaId+"&callback=?";
    jQuery.getJSON(url,null,function call(result){  
          setCity(result); 
      });
    
   }else if( name=='county'){
    clearSel(document.getElementById("toCounty")); //清空城区
    var city = document.getElementById("toCity");
    if(city.options[city.selectedIndex].value == "") return;
    var areaId = city.options[city.selectedIndex].value;
    
    var url ="<%=request.getContextPath() %>/getAreaJSON?areaId="+areaId+"&callback=?";
    jQuery.getJSON(url,null,function call(result){  
          setCounty(result); 
      });
      
   }
  }
 
  //当改变省份时设置城市
  function setCity(result){
  
  var city = document.getElementById("toCity");
  
  jQuery.each(result.data, function(i, area){
         var value = area.id;
    var text = area.name;
    var option = new Option(text,value);
    city.options.add(option);
    }); 
   
  }
  
  //当改变省份时设置城市
  function setCounty(result){
 
  var county = document.getElementById("toCounty");
  
  jQuery.each(result.data, function(i, area){
         var value = area.id;
    var text = area.name;
    var option = new Option(text,value);
    county.options.add(option);
    }); 
   
  }
 
  // 清空下拉列表
  function clearSel(oSelect){
     
  while(oSelect.childNodes.length>0){
   oSelect.removeChild(oSelect.childNodes[0]);
  }
        
  }

 

</script>

 

  <tr>
  <td height="28" colspan="3">
   <select name="toProvince" id="toProvince" onChange="getArea('city')" class="STYLE5" onFocus="doOnFocus(this);">
    <option value="" selected>请选择省份...</option>
   </select>         
  </td>
         </tr>

         <tr>
  <td height="28" colspan="3">              
   <select name="toCity" id="toCity" class="board" onChange="getArea('county')" onFocus="doOnFocus(this);">
    <option value="">请选择城市...</option>
   </select>        
  </td>    
         </tr>
        
         <tr>
  <td class="STYLE3">
   <select name="toCounty" id="toCounty" class="board"  onfocus="doOnFocus(this);">
    <option value="">请选择城区...</option>
   </select>        
  </td>
 </tr>

 

JAVA部分代码 Servlet

 

 response.setContentType("text/xml;charset=utf-8");
  response.setHeader("Pragma","No-cache");
  response.setDateHeader("Expires",0);
  response.setHeader("Cache-Control","no-cache");    
  PrintWriter out=response.getWriter();

  String areaId = request.getParameter("areaId");
  
  if(areaId==null || areaId.trim().length()<=0){
   //sb.append("<data><error>系统错误地区id为空</error></data>");
   //out.print(sb.toString());
   return;
  }  
  

  //注意这个是为了解决跨域访问的问题
  String callback = request.getParameter("callback");   
  
  try {

   List areaList = AreaService.getInstance().getAreasByParentId(Integer.parseInt(areaId));

   // 取集合
   JSONArray jsonArray = JSONArray.fromObject(areaList);

   JSONObject jsobjcet = new JSONObject();

   jsobjcet.put("data", jsonArray);
   
   response.getWriter().write(callback+"("+jsobjcet.toString()+");");

   log.info(callback+"("+jsobjcet.toString()+");");
   
   
  } catch (IOException e) {
   e.printStackTrace();
  }
    

 

DAO部分代码

public List getAreasByParentId(int parentId) {
  Connection conn=null;
  Statement stm=null;
  ResultSet rs=null;
  List<AreaInfo> list = new ArrayList<AreaInfo>();
  try{
   conn = ConnectionPool.getConnection();
   if( conn == null ) throw new Exception("DataBase connection error");
   stm = conn.createStatement();
   String sql ="select * from n_area where parent_id =" + parentId;
   rs = stm.executeQuery(sql);
   AreaInfo areaInfo = null;
   while( rs.next() ) {
    areaInfo= new AreaInfo();
    areaInfo.setId(rs.getInt("id"));
    areaInfo.setName(rs.getString("name"));
    areaInfo.setParentId(rs.getInt("parent_id"));
    list.add(areaInfo);
   }
  }catch(Exception e){
   log.error("getAreasByParentId() error:"+e.getMessage());
  }finally{
   ConnectionPool.release(conn,stm,rs); //释放资源
  }
  return list;
 }

 

 

数据表结构

CREATE TABLE n_area (
  id int(11) NOT NULL,
  name varchar(20) ,
  parent_id int(11),
  )

记录

 

INSERT INTO n_area VALUES ('180', '内蒙古', '0');
INSERT INTO n_area VALUES ('181', '
呼和浩特
', '180');
INSERT INTO n_area VALUES ('182', '
吉林省
', '0');
INSERT INTO n_area VALUES ('183', '
*省
', '0');
INSERT INTO n_area VALUES ('184', '
*
', '183');
INSERT INTO n_area VALUES ('185', '
吉林市
', '182');
INSERT INTO n_area VALUES ('215', '
其他地区
', '213');
INSERT INTO n_area VALUES ('187', '
其他地区
', '1');
INSERT INTO n_area VALUES ('188', '
其他地区
', '30');
INSERT INTO n_area VALUES ('189', '
其他地区
', '31');
INSERT INTO n_area VALUES ('190', '
其他地区
', '32');
INSERT INTO n_area VALUES ('191', '
其他地区
', '33');
INSERT INTO n_area VALUES ('192', '
其他地区
', '34');
INSERT INTO n_area VALUES ('193', '
其他地区
', '35');
INSERT INTO n_area VALUES ('194', '
其他地区
', '36');
INSERT INTO n_area VALUES ('195', '
其他地区
', '37');
INSERT INTO n_area VALUES ('196', '
其他地区
', '38');
INSERT INTO n_area VALUES ('197', '
其他地区
', '39');
INSERT INTO n_area VALUES ('198', '
其他地区
', '40');
INSERT INTO n_area VALUES ('199', '
其他地区
', '41');
INSERT INTO n_area VALUES ('200', '
其他地区
', '42');
INSERT INTO n_area VALUES ('201', '
其他地区
', '43');
INSERT INTO n_area VALUES ('202', '
其他地区
', '44');
INSERT INTO n_area VALUES ('203', '
其他地区
', '94');
INSERT INTO n_area VALUES ('204', '
其他地区
', '136');
INSERT INTO n_area VALUES ('205', '
其他地区
', '178');
INSERT INTO n_area VALUES ('206', '
其他地区
', '180');
INSERT INTO n_area VALUES ('207', '
其他地区
', '182');
INSERT INTO n_area VALUES ('214', '
拉萨
', '213');
INSERT INTO n_area VALUES ('210', '
其他地区
', '45');
INSERT INTO n_area VALUES ('211', '
其他地区
', '46');
INSERT INTO n_area VALUES ('212', '
其他地区
', '86');
INSERT INTO n_area VALUES ('220', '
新三区
', '184');
INSERT INTO n_area VALUES ('219', '
新二区
', '184');
INSERT INTO n_area VALUES ('221', '
天河区
', '4');
INSERT INTO n_area VALUES ('222', '
越秀区
', '4');
INSERT INTO n_area VALUES ('223', '
海珠区', '4');

 

附件中有相应的jar包

json-lib-2.1-jdk15.jar 是主要的

  • commons-beanutils.jar (184.2 KB)
  • commons-lang-2.1.jar (202.9 KB)
  • commons-collections-3.2.jar (557.9 KB)
  • json-lib-2.1-jdk15.jar (195.3 KB)
  • commons-logging.jar (51.7 KB)