通过AJAX实现三级下拉框查询省市等

1. 一个单独的测试界面:

[java]  view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'new.jsp' starting page</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!--  
  20.     <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">  
  21.     -->  
  22.   
  23.     <mce:script type="text/javascript" src="resources/jquery.js" mce_src="resources/jquery.js"></mce:script>  
  24.   
  25.   </head>  
  26.     <body>  
  27.         <select id="Select1" name="Select1" οnchange="selectProvince();"></select>  
  28.         <select id="Select2" name="Select2" οnchange="selectArea();"></select>  
  29.         <select id="Select3" name="Select3"></select>  
  30.           
  31.     </body>  
  32. </html>  
  33.   
  34. <mce:script type="text/javascript"><!--  
  35.       
  36.     window.onload = function() {  
  37.         initArea();   
  38.     }  
  39.       
  40.     function initArea() {  
  41.         /*获取,引用三个下拉框 */  
  42.         var dropElement1=document.getElementById("Select1");   
  43.         var dropElement2=document.getElementById("Select2");   
  44.         var dropElement3=document.getElementById("Select3");   
  45.       
  46.         /*自定义一个方法 把传进来的对象清除 这里清除了三个下拉所有框的选项*/    
  47.         removeDropDownList(dropElement1);  
  48.         removeDropDownList(dropElement2);  
  49.         removeDropDownList(dropElement3);  
  50.           
  51.         var pOption = document.createElement("option");  
  52.         pOption.value = "0";  
  53.         pOption.text = "全国";  
  54.         dropElement1.add(pOption);  
  55.       
  56.         var cOption = document.createElement("option");  
  57.         cOption.value = "0";  
  58.         cOption.text = "全部市";  
  59.         dropElement2.add(cOption);  
  60.           
  61.         var aOption = document.createElement("option");  
  62.         aOption.value = "0";  
  63.         aOption.text = "全区县";  
  64.         dropElement3.add(aOption);  
  65.           
  66.         var url = "servlet/XmlForAJAX";   
  67.         url = encodeURI(encodeURI(url));  
  68.         doAjax(url,null,null,dropElement1,dropElement2,dropElement3);      
  69.     }  
  70.       
  71.       
  72.     /** 
  73.      * 当选择一个省的时候自动的添加该省下的市 
  74.      */      
  75.     function selectProvince() {  
  76.         var dropElement1=document.getElementById("Select1");   
  77.         //获取选中项的内容  
  78.         var provinceName=dropElement1.options[dropElement1.selectedIndex].text;  
  79.           
  80.         var dropElement2=document.getElementById("Select2");   
  81.         var dropElement3=document.getElementById("Select3");  
  82.           
  83.         removeDropDownList(dropElement2);  
  84.         removeDropDownList(dropElement3);  
  85.           
  86.         var cOption = document.createElement("option");  
  87.         cOption.value = "0";  
  88.         cOption.text = "全部市";  
  89.         dropElement2.add(cOption);  
  90.           
  91.         var aOption = document.createElement("option");  
  92.         aOption.value = "0";  
  93.         aOption.text = "全区县";  
  94.         dropElement3.add(aOption);          
  95.   
  96.         var url = "servlet/XmlForAJAX";   
  97.         url = encodeURI(encodeURI(url));  
  98.         doAjax(url,provinceName,null,dropElement1,dropElement2,dropElement3);           
  99.     }  
  100.       
  101.     /** 
  102.      * 当选择一个省的时候自动的添加该省下的市 
  103.      */   
  104.     function selectArea() {  
  105.         var dropElement1=document.getElementById("Select1");   
  106.         var provinceName=dropElement1.options[dropElement1.selectedIndex].text;  
  107.         var dropElement2=document.getElementById("Select2");   
  108.         var cityName=dropElement2.options[dropElement2.selectedIndex].text;  
  109.           
  110.         var dropElement3=document.getElementById("Select3");  
  111.         removeDropDownList(dropElement3);  
  112.         var aOption = document.createElement("option");  
  113.         aOption.value = "0";  
  114.         aOption.text = "全区县";  
  115.         dropElement3.add(aOption);  
  116.           
  117.         var url = "servlet/XmlForAJAX";   
  118.         url = encodeURI(encodeURI(url));  
  119.         doAjax(url,provinceName,cityName,dropElement1,dropElement2,dropElement3);    
  120.     }  
  121.       
  122.       
  123.     //AJAX操作类  
  124.     function doAjax(url,provinceName,cityName,dropElement1,dropElement2,dropElement3) {  
  125.         $.ajax({  
  126.                     type:"POST",  
  127.                     secureuri:false,  
  128.                     dataType:"xml",  
  129.                     url: url,  
  130.                     timeout:1000,  
  131.                     success:function(xml) {  
  132.                           
  133.                         $(xml).find("province").each(function(i){  
  134.                              var province = $(this).attr("name");  
  135.                              //alert(province);  
  136.                              if(provinceName == null || provinceName == "") {  
  137.                                  var pOption = document.createElement("option");  
  138.                                  pOption.value = province;  
  139.                                  pOption.text = province;  
  140.                                  dropElement1.add(pOption);  
  141.                              }  
  142.                                
  143.                              if(provinceName != null && provinceName != "") {  
  144.                                   if(provinceName == province) {  
  145.                                       $(this).find("city").each(function(j){  
  146.                                           var city = $(this).attr("name");  
  147.                                           //alert("city is " + city);  
  148.                                           if(cityName == null || cityName == "") {  
  149.                                               var pOption = document.createElement("option");  
  150.                                               pOption.value = city;  
  151.                                               pOption.text = city;  
  152.                                               dropElement2.add(pOption);  
  153.                                           }  
  154.                                         
  155.                                           if(cityName != null && cityName != null) {  
  156.                                               if(cityName == city) {  
  157.                                                   $(this).find("area").each(function(k){  
  158.                                                       var area = $(this).attr("name");  
  159.                                                       //alert("area is " + area);  
  160.                                                       var pOption = document.createElement("option");  
  161.                                                       pOption.value = area;  
  162.                                                       pOption.text = area;  
  163.                                                       dropElement3.add(pOption);  
  164.                                                  });        
  165.                                               }  
  166.                                          }  
  167.                                       });  
  168.                                   }  
  169.                              }  
  170.                         });  
  171.                     },    
  172.                     error:function(xml) {  
  173.                         alert("error.");      
  174.                     }    
  175.           });  
  176.     }  
  177.       
  178.       
  179.     /* 清除下拉框的选项 */  
  180.     function removeDropDownList(obj) {  
  181.         //如果obj不为空的时候  
  182.         if(obj) {  
  183.             var length = obj.options.length;  
  184.             if(length > 0) {  
  185.                 for(var i=length;i >= 0;i--) {  
  186.                     obj.remove(i);  
  187.                 }  
  188.             }  
  189.         }  
  190.     }  
  191.       
  192. // --></mce:script>  

 

2. servlet

[java]  view plain copy
  1. package service;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.PrintWriter;  
  7.   
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12.   
  13. import upload.FileOperation;  
  14.   
  15. public class XmlForAJAX extends HttpServlet {  
  16.   
  17.     /** 
  18.      * Constructor of the object. 
  19.      */  
  20.     public XmlForAJAX() {  
  21.         super();  
  22.     }  
  23.   
  24.     /** 
  25.      * Destruction of the servlet. <br> 
  26.      */  
  27.     public void destroy() {  
  28.         super.destroy(); // Just puts "destroy" string in log  
  29.         // Put your code here  
  30.     }  
  31.   
  32.     /** 
  33.      * The doGet method of the servlet. <br> 
  34.      * 
  35.      * This method is called when a form has its tag value method equals to get. 
  36.      *  
  37.      * @param request the request send by the client to the server 
  38.      * @param response the response send by the server to the client 
  39.      * @throws ServletException if an error occurred 
  40.      * @throws IOException if an error occurred 
  41.      */  
  42.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  43.             throws ServletException, IOException {  
  44.   
  45.         response.setContentType("text/html");  
  46.         PrintWriter out = response.getWriter();  
  47.         out  
  48.                 .println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">");  
  49.         out.println("<HTML>");  
  50.         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");  
  51.         out.println("  <BODY>");  
  52.         out.print("    This is ");  
  53.         out.print(this.getClass());  
  54.         out.println(", using the GET method");  
  55.         out.println("  </BODY>");  
  56.         out.println("</HTML>");  
  57.         out.flush();  
  58.         out.close();  
  59.     }  
  60.   
  61.     /** 
  62.      * The doPost method of the servlet. <br> 
  63.      * 
  64.      * This method is called when a form has its tag value method equals to post. 
  65.      *  
  66.      * @param request the request send by the client to the server 
  67.      * @param response the response send by the server to the client 
  68.      * @throws ServletException if an error occurred 
  69.      * @throws IOException if an error occurred 
  70.      */  
  71.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  72.             throws ServletException, IOException {  
  73.   
  74.         response.setHeader("Content-Type","text/xml; charset=UTF-8");     
  75.         PrintWriter out = response.getWriter();  
  76.           
  77.         FileOperation f = new FileOperation();  
  78.         String str = "";  
  79.         try {  
  80.             InputStream in = f.getResourceAsStream("service/area.xml");  
  81.               
  82. /*          if(in != null) { 
  83.                 System.out.println("不是空的"); 
  84.             } else { 
  85.                 System.out.println("是空的。"); 
  86.             }*/  
  87.               
  88.             int i = -1;  
  89.             ByteArrayOutputStream bis = new ByteArrayOutputStream();  
  90.             while((i = in.read()) != -1) {  
  91.                 bis.write(i);  
  92.             }  
  93.               
  94.             //System.out.println(bis.toString("UTF-8"));  
  95.             out.print(bis.toString("UTF-8"));  
  96.         } catch (Exception e) {  
  97.             // TODO Auto-generated catch block  
  98.             e.printStackTrace();  
  99.         }  
  100.           
  101. /*      StringBuffer bf = new StringBuffer();    
  102.         bf.append("<?xml version=/"1.0/" encoding=/"UTF-8/"?>")    
  103.         .append("<stulist>").append("<student email=/"1@1.com/">").append("<name>zhangsan</name>").append("<id>1</id>")    
  104.         .append("</student>").append("<student email=/"2@2.com/">").append("<name>lisi</name>").append("<id>2</id>")    
  105.         .append("</student>").append("</stulist>");   
  106.         System.out.println(bf.toString());   
  107.         out.print(bf.toString());*/   
  108.           
  109.         out.flush();  
  110.         out.close();  
  111.     }  
  112.   
  113.     /** 
  114.      * Initialization of the servlet. <br> 
  115.      * 
  116.      * @throws ServletException if an error occurs 
  117.      */  
  118.     public void init() throws ServletException {  
  119.         // Put your code here  
  120.     }  
  121.   
  122. }  

 

3. XML文件,可以按照以下格式多添加几个市

[java]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <root name="中国">  
  4.     <province name="北京" postcode="beijing" index="1" id="1">  
  5.         <city name="北京" postcode="100000" index="1">  
  6.             <area name="北京市" postcode="100000" price="1" index="1"/>  
  7.             <area name="门头沟区" postcode="102300" index="2"/>  
  8.             <area name="房山区" postcode="102400" index="3"/>  
  9.             <area name="顺义区" postcode="101300" index="4"/>  
  10.             <area name="通州区" postcode="101100" index="5"/>  
  11.             <area name="昌平区" postcode="102200" index="6"/>  
  12.             <area name="密云县" postcode="101500" index="7"/>  
  13.             <area name="延庆县" postcode="102100" index="8"/>  
  14.             <area name="大兴县" postcode="102600" index="9"/>  
  15.             <area name="怀柔县" postcode="101400" index="10"/>  
  16.             <area name="平谷县" postcode="101200" index="11"/>  
  17.         </city>  
  18.     </province>  
  19. </root>  

转载于:https://my.oschina.net/u/219582/blog/59461

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值