ajax+servlet实现二级联动(以省与城市为例)(转)

ajax+servlet实现二级联动(以省份与城市为例)(转)

1.实现思路:

    在下拉列表框中编写js函数触发onchange事件,在这js函数中将选中的name值通过ajax传给后台servlet,在servlet中通过request.getParameter("name")获得选中的name,调用后台的方法得到相应的城市列表(此例没有数据库)。然后如果查到响应的城市的话将其列表组成一个用"#"号分割的字符串str,将其放到response的Writer中。然后在回调函数中接受应答字符串str,调用split("#")方法得到相应的城市数组,然后取得index.jsp的下拉列表框ID,将相应的城市用循环动态的加入到城市列表框中。

2.具体例子

(1)index.jsp

 

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%  
  3.     String path = request.getContextPath();  
  4. %>  
  5. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  6. <html>  
  7.     <head>  
  8.         <title>以城市与省份为例,用ajax实现二级联动</title>  
  9.     </head>  
  10.     <mce:script type="text/javascript"><!--  
  11.   function $(id){  
  12.       return document.getElementById(id);  
  13.   }  
  14.   var xmlHttp;  
  15.   //根据浏览器创建xmlHttpRequest对象  
  16.   function getXmlHttpRequest() {  
  17.   //针对FireFox,Mozillar,Opera,Safari,IE7,IE8  
  18.   if(window.XMLHttpRequest)   
  19.       return new XMLHttpRequest();  
  20.   //针对IE5,IE5.5,IE6  
  21.   else if (window.ActiveXObject){    
  22.        //两个可以用于创建XMLHTTPRequest对象的控件名称,保存在一个JS数组中。  
  23.        var activexName = ["MSXML2.XMLHTTP","Microsoft.XMLHTTP"];  
  24.        for(var i = 0; i<activexName.length; i++){  
  25.            //取出一个控件名进行创建,如果成功就终止循环  
  26.            try{  
  27.               return new ActiveXObject(activexName[i]);  
  28.               break;  
  29.            }catch(e){  
  30.            return null;  
  31.            }  
  32.        }  
  33.        }         
  34.   }  
  35.   function getCity(){  
  36.            xmlHttp=getXmlHttpRequest();  
  37.              var url="GetCity?provinceName="+$("provinceid").value;  
  38.            // 注册回调函数,只写函数名,不能写括号,写括号表示调用函数  
  39.            xmlHttp.onreadystatechange = getResult;  
  40.            // 确定发送请求的方式和URL以及是否同步执行下段代码  
  41.            xmlHttp.open("GET", url, true);  
  42.            //发送数据,开始和服务器进行交互  
  43.            xmlHttp.send(null);  
  44.   }  
  45.   //回调函数  
  46.   function getResult(){  
  47.       if (xmlHttp.readyState == 4) { // 判断对象状态  
  48.             if (xmlHttp.status == 200) { // 信息已经成功返回,开始处理信息  
  49.          var cityArray;  
  50.          var city=$("cityid");  
  51.          var len=city.length;  
  52.          //要将城市下拉列表框清空  
  53.          if(len!=0){  
  54.               city.innerHTML="";  
  55.          }  
  56.          //如果应答字符串含有"#"号的话进行分割,并将其内容动态的添加到城市下拉列表框中  
  57.          if(xmlHttp.responseText.indexOf("#")!=-1){  
  58.                        cityArray=xmlHttp.responseText.split("#");  
  59.             for(var i=0;i<cityArray.length;i++){  
  60.              var option=new Option(cityArray[i],cityArray[i]);  
  61.              city.add(option);  
  62.          }  
  63.          }  
  64.          else{  
  65.             cityArray=xmlHttp.responseText;  
  66.             var option=new Option(cityArray,cityArray);  
  67.             city.add(option);  
  68.         }  
  69.         } else {   
  70.                   alert("请求的出错啦!");  
  71.        }  
  72.   }  
  73.   }  
  74.     
  75. // --></mce:script>  
  76.     <body>  
  77.         <form>  
  78.             选择省份:  
  79.             <select id="provinceid" onchange="getCity()">  
  80.                 <option value="none">  
  81.                     请选择  
  82.                 </option>  
  83.                 <option value="guangdong">  
  84.                     广东  
  85.                 </option>  
  86.                 <option value="ningxia">  
  87.                     宁夏  
  88.                 </option>  
  89.             </select>  
  90.             城市:  
  91.             <select id="cityid">  
  92.                 <option value="none">  
  93.                     没有数据  
  94.                 </option>  
  95.             </select>  
  96.         </form>  
  97.     </body>  
  98. </html>  

 

(2)GetCity.java

 

  1. import java.io.IOException;  
  2. import java.io.PrintWriter;  
  3. import javax.servlet.ServletException;  
  4. import javax.servlet.http.HttpServlet;  
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7.   
  8. public class GetCity extends HttpServlet {  
  9.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  10.             throws ServletException, IOException {  
  11.         response.reset();  
  12.         String name=request.getParameter("provinceName")==null?"":request.getParameter("provinceName");  
  13.         System.out.print(name);  
  14.         String str="";  
  15.         if(name.trim().equals("guangdong")){  
  16.             str="广州#深圳#东莞#中山#珠海#惠东";  
  17.         }else if(name.trim().equals("ningxia")){  
  18.             str="银川#吴忠#中卫#中宁#固原";  
  19.         }else{  
  20.             str="没有数据";  
  21.         }  
  22.         response.setContentType("text/html");  
  23.         response.setCharacterEncoding("utf-8");  
  24.         response.getWriter().write(str);  
  25.         response.getWriter().flush();  
  26.     }  
  27.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  28.             throws ServletException, IOException {  
  29.         doGet(request,response);  
  30.     }  
  31. }  

 

(3)web.xml

 

 

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.   <servlet>  
  8.     <description>This is the description of my J2EE component</description>  
  9.     <display-name>This is the display name of my J2EE component</display-name>  
  10.     <servlet-name>GetCity</servlet-name>  
  11.     <servlet-class>GetCity</servlet-class>  
  12.   </servlet>  
  13.   <servlet-mapping>  
  14.     <servlet-name>GetCity</servlet-name>  
  15.     <url-pattern>/GetCity</url-pattern>  
  16.   </servlet-mapping>  
  17.   <welcome-file-list>  
  18.     <welcome-file>index.jsp</welcome-file>  
  19.   </welcome-file-list>  
  20. </web-app>