丄諦啲仇魜ヤ
如 果 敌 人 让 你 生 气 , 那 说 明 你 没 有 胜 他 的 把 握!
posts - 6,comments - 56,trackbacks - 1

ajax巨好用,4级级联菜单的解决 (转) http://www.blogjava.net/liaojiyong/archive/2006/07/24/59821.html

为解决省、市、区、区域4级级联菜单,在网上搜索了大量的级联菜单解决方案,也请教过不少朋友,要么过于复杂,要么过于占内存,未果。

在建议下,悉心读《ajax基础教程》4余遍,方有与ajax相识恨晚之感,唯一的感慨就是好用好用绝对好用。

现在把已经可以正常运行的例子的核心代码分享:
客户端ajax代码如下:
<script type="text/javascript">
        var xmlHttp;
        var domainId;
        var type;
        
        function refreshList(typesource) {
            createXMLHttpRequest();
            type 
= typesource;
            
if ("p" == type) {
                getSelectedId(
"province_select");
            } 
else if("c" == type) {
                getSelectedId(
"city_select");
            } 
else if("s" == type) {
                getSelectedId(
"section_select");
            } 
            var url 
= "enterpriseManage2.html?method=retrieve&ts=" + new Date().getTime();
            var queryStr 
= "domainId=" + domainId;
            alert(queryStr);
            xmlHttp.onreadystatechange
=handleStateChange;
            xmlHttp.open(
"POST", url);
            xmlHttp.setRequestHeader(
"Content-Type","application/x-www-form-urlencoded;");
            xmlHttp.send(queryStr);
        }
        
        function handleStateChange() {
            
if (xmlHttp.readyState == 4) {
                
if (xmlHttp.status == 200) {
                    updateList();
                }
            }
         }
         
         function getSelectedId(elementId) {
             alert(
"elementId: " + elementId);
             
//var selectedId = null;
             var options = document.getElementById(elementId).childNodes;
             var option 
= null;
             
for (var i = 0, n = options.length; i < n; i++) {
                 option 
= options[i];
                 
if (option.selected) {
                     domainId 
= option.value;
                     
//return selectedId;
                 }
             }
         }
         
         function updateList() {
             alert(
"type: " + type);
             
if ("p" == type) {
                 var select 
= document.getElementById("city_select");
                 var options 
= xmlHttp.responseXML.getElementsByTagName("domain");
                 for (var i = 0, n = options.length; i < n; i++) {
                     select.appendChild(createElementWithValue(options[i]));
                 }
             } 
else if("c" == type) {
                 var select 
= document.getElementById("section_select");
                 var options 
= xmlHttp.responseXML.getElementsByTagName("domain");
                 for (var i = 0, n = options.length; i < n; i++) {
                     select.appendChild(createElementWithValue(options[i]));
                 }    
             } 
else if("s" == type) {
                 var select 
= document.getElementById("appointDomain");
                 var options 
= xmlHttp.responseXML.getElementsByTagName("domain");
                 
for (var i = 0, n = options.length; i < n; i++) {
                     select.appendChild(createElementWithValue(options[i]));
                 }    
             }
         }

         
         function createElementWithValue(text) {
             var element 
= document.createElement("option");
             element.setAttribute(
"value", text.getAttribute("id"));
             var text 
= document.createTextNode(text.firstChild.nodeValue);
             element.appendChild(text);
             
return element;
         }
        
        function createXMLHttpRequest() {
            
if(window.XMLHttpRequest) {
                    xmlHttp = new XMLHttpRequest();
                } 
else if (window.ActiveXObject) {
                    try {
                        xmlHttp 
= new ActiveXObject("Msxml2.XMLHTTP");
                    } 
catch (e) {
                        
try {
                            xmlHttp 
= new ActiveXObject("Microsoft.XMLHTTP");
                        } 
catch (e) {
                        }
                    }
                }
        }

    
</script>


页面调用处代码如下:
<td align="left" class="list_content" width="75%">
    省
   
<select id="province_select" name="province_select" onchange="refreshList('p');"> 
        
<option value="" SELECTED>请选择</option>
            
<%
                java.util.Iterator it 
= ((java.util.List)request.getAttribute("province_options")).iterator();
               
while (it.hasNext()) {
                    Province province 
= (Province)it.next();
             
%>
             
<option value=<%=province.getId()%>><%=province.getName()%></option>
             
<%
                 }
             
%>
   
</select>
    市
   
<select id="city_select" name="city_select" onchange="refreshList('c');">      
         <option value="" SELECTED>请选择</option>
   
</select>
    区
   
<select id="section_select" name="section_select" onchange="refreshList('s');"> 
        
<option value="" SELECTED>请选择</option>
   
</select>
    区域
   
<select id="appointDomain" name="appointDomain"> 
        
<option value="" SELECTED>请选择</option>
   
</select>
</td>


服务器端action(Struts)代码如下:
 1 public ActionForward retrieve(ActionMapping mapping, ActionForm actionForm,
 2             HttpServletRequest request, HttpServletResponse response) {
 3         String domainId = request.getParameter("domainId");
 4         DomainFactory factory = DomainFactory.getInstance();
 5         Object domain = factory.getDomain(domainId);
 6         StringBuffer responseXML = new StringBuffer("<domains>");
 7         if(domain instanceof Province) {
 8             Province province = (Province)domain;
 9             Iterator it = province.getCities().iterator();
10             while (it.hasNext()) {
11                 City city = (City)it.next();
12                 responseXML.append("<domain");
13                 responseXML.append(" id='" + city.getId());
14                 responseXML.append("'>");
15                 responseXML.append(city.getName());
16                 responseXML.append("</domain>");
17             }
18         } else if(domain instanceof City) {
19             City city = (City)domain;
20             Iterator it = city.getSections().iterator();
21             while (it.hasNext()) {
22                 Section section = (Section)it.next();
23                 responseXML.append("<domain");
24                 responseXML.append(" id='" + section.getId());
25                 responseXML.append("'>");
26                 responseXML.append(section.getName());
27                 responseXML.append("</domain>");
28             }
29         } else if (domain instanceof Section) {
30             Section section = (Section)domain;
31             Iterator it = section.getRegions().iterator();
32             while (it.hasNext()) {
33                 Region region = (Region)it.next();
34                 responseXML.append("<domain");
35                 responseXML.append(" id='" + region.getId());
36                 responseXML.append("'>");
37                 responseXML.append(region.getName());
38                 responseXML.append("</domain>");
39             }
40         } 
41         responseXML.append("</domains>");
42         response.setContentType("text/xml");
43         try {
44             PrintWriter out = (PrintWriter)response.getWriter();
45             out.write(responseXML.toString());
46             System.out.println(responseXML.toString());
47             //out.flush();
48         } catch (IOException e) {
49             //do nothing
50             e.printStackTrace();
51         }
52         return null;
53     }




我写自己的二级联动--------------------------------------------------------------------------------------------------

<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>污控地区信息页</title>
  <script language="JavaScript" type="text/javascript" src="../../include/comFace.js"></script>
  <link href="../../include/css.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
<!--
var xmlHttp=false;

 function createXMLHttpRequest(){  
        if(window.XMLHttpRequest) { //Mozilla 浏览器
                  xmlHttp = new XMLHttpRequest();
          }else if (window.ActiveXObject){ // IE浏览器
      try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
                  xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
             } catch (e) {}
      }
        }
    }

  function getSelectedId(value) {
       // var queryStr = "selectYear=" + value;      
        createXMLHttpRequest();
        xmlHttp.open("POST","addrInfoEditServlet.jsp?selectYear="+value,true);
        xmlHttp.onreadystatechange=callbackfunction;
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlHttp.send(null);
      }
  function callbackfunction(){
         if(xmlHttp.readyState==4){// readystate是错误的写法 
           if(xmlHttp.status==200){    
              var data=xmlHttp.responseXML;
              var select = document.getElementById("addrName");
              clearData();
              var options = xmlHttp.responseXML.getElementsByTagName("domain");
              for (var i = 0; i < options.length; i++) {
                      select.appendChild(createElementWithValue(options[i]));
                  }
            }
        }
      }
  function createElementWithValue(text) {
             var element = document.createElement("option");
             element.setAttribute("value", text.getAttribute("id"));
             var text = document.createTextNode(text.firstChild.nodeValue);
             element.appendChild(text);
             return element;
         }
   function clearData() {     
       var select = document.getElementById("addrName");     
       var ind = select.childNodes.length;
       for (var i = ind - 1; i >= 2 ; i--) {
           select.removeChild(select.childNodes[i]);      
       }
    }       
  function checkArea(){
     var v=document.getElementById("addrName").value;
     var y=document.getElementById("selectYear").value;
     if(y=="0"){
       alert("请选择日期!");
       return false;    
     }

     if(v=="0"){
       alert("请选择地区名称!");
       return false;    
     }
     return true;
   }
 
//-->
</script>
 </head>
 <body>
<form name="form1" method="post" action="addrInfoEdit.jsp" >

      <select name="selectYear" id="selectYear" onchange="getSelectedId(this.value) " class="text02" size=1 style="width:77">
            <option value='0'>选择年份</option>
             <%for(int i=2007;i<now+20;i++)
                 { 
             %>
              <option value="<%=i %>" ><%= i %></option>
               <%}%> 
       </select>

      <select id="addrName" name="addrName" style="width: 77" >       
                   <option value="0" selected>--请选择--</option>
         </select>
<input  type="submit" onclick="return checkArea();">

</form>
</body>

addrInfoEditServlet.jsp

<%
    request.setCharacterEncoding("UTF-8");
    String selectYear=StringUtil.removeNull(request.getParameter("selectYear"));//获得年份
  
       AddrInfoHelper addrInfoHelper = ServiceLocator.getPollute().getAddrInfoHelper();
       StringBuffer keys=new StringBuffer();
  ArrayList rowsList=(ArrayList)  addrInfoHelper.getAll(selectYear,"1");
  Iterator rows = rowsList.iterator();
   while(rows.hasNext()){
           AddrInfo row = (AddrInfo) rows.next();
                        keys.append(row.getAddrName()+"&");//将表中已存在地区的的ID取出放入stringBuffer中
  } 
  String [] newKeys=  keys.toString().split("&");//数组
  ConstantService con = ServiceUtil.getConstantService();
  Map areaMap=con.getArea(); //取出的是含有id和地区名的MAP
      Map newAreaMap=new HashMap();//备用
  Set entry=areaMap.entrySet();
  Iterator it=entry.iterator();
  while(it.hasNext()){ 
       Map.Entry me=(Map.Entry)it.next();
    newAreaMap.put(me.getKey(),me.getValue());//将原来的areaMap键值存放到新的MAP中
  }
  for(int i=0;i<newKeys.length;i++){
                    newAreaMap.remove(newKeys[i]);//去掉已存在的
         }
     response.setContentType("text/xml; charset=UTF-8");
     response.setHeader("Cache-Control", "no-cache");
  out.println("<domains>");
  Set entrys=newAreaMap.entrySet();
  Iterator its=entrys.iterator();
  while(its.hasNext()){ 
    Map.Entry mes=(Map.Entry)its.next();
    out.println("<domain id='"+mes.getKey()+"'>"+mes.getValue()+"</domain>");
  }
  out.println("</domains>");
  out.flush();
     out.close();
 
 
 
          
       
  

%>



posted on 2008-03-25 09:26 Crying 阅读(1471) 评论(0)  编辑  收藏 所属分类: AJAX

只有注册用户登录后才能发表评论。


网站导航: