全国统一服务热线:400-633-9193

js使用xml数据载体实现城市省份二级联动效果

    网络     2017-11-21    1337

本文实例为大家分享了使用xml数据载体实现城市省份二级联动的具体代码,供大家参考,具体内容如下

首先写好前台页面testProvince.jsp,将请求通过open、send发送到服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <base href="<%=basePath%>" rel="external nofollow" >
  <title>二级联动</title>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">  
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
  <style type="text/css">
    select{
      width:111px;
    }
  </style>
 </head>
   
 <body>
    <select id="provinceID">
    <option>选择省份</option>
    <option>湖南</option>
    <option>广东</option>
    </select> 
        
    <select id="cityID">
      <option>选择城市</option>
    </select> 
 </body>
 <script type="text/javascript">
    //创建ajax对象
    function createAjax(){
      var ajax = null;
      try{
        ajax = new ActiveXObject("microsoft.xmlhttp");
      }catch(e){
        try{
          ajax = new XMLHttpRequest();
        }catch(e1){
          alert("请更换浏览器");
        }
      }
      return ajax;
    }
 </script>
   
 <script type="text/javascript">
    document.getElementById("provinceID").onchange = function(){
      //清空城市除了第一项
      var cityElem = document.getElementById("cityID");
      cityElem.options.length = 1;
        
      //获取选中的省份
      var province = this.value;
      //进行编码处理
      province = encodeURI(province);
      if("选择省份" != province){
        var ajax = createAjax();
        //提交方式为GET
        var method = "GET";
        //提交路径为servlet路径
        var url = "${pageContext.request.contextPath}/ProvinceServlet?time=" + new Date().getTime()+
            "&province=" +province;
        //准备发送异步请求
        ajax.open(method, url);
        //由于是get请求,所以不需要设置请求头
        //发送请求
        ajax.send(null);
          
        //监听服务器响应状态的变化
        ajax.onreadystatechange = function(){
          //响应状态为4 表示ajax已经完全接受到服务器的数据了
          if(ajax.readyState == 4){
            //接收到的数据正常
            if(ajax.status == 200){
              //获取服务器传来的html数据
              var xmlDocument = ajax.responseXML;
              //进行dom操作解析xml
              //解析xml数据
              var citys = xmlDocument.getElementsByTagName("city");
              for(var i = 0; i< citys.length;i++){
                //获取xml中的值 :不能用innerHTML,要用nodeValue
                var city = citys[i].firstChild.nodeValue;
                //创建option
                var optElement = document.createElement("option");
                optElement.innerHTML = city;
                //获取city
                var cityElems = document.getElementById("cityID");
                cityElems.appendChild(optElement);
              }
                
            }
          }
        }
      }
        
    }
      
      
 </script>
</html>

然后在后台ProvinceServlet中通过GET方式获取请求,将返回的数据以O(输出)流的方式发送出去,上面代码的ajax.responseXML获取输出的数据,并进行dom操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class ProvinceServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    resp.setCharacterEncoding("utf-8");
    String province = req.getParameter("province");
    //重新编码
    province = new String(province.getBytes("ISO-8859-1"),"utf-8");
    //设置格式为xml
    resp.setContentType("text/xml;charset=utf-8");
    //获取字符输出流
    PrintWriter pw = resp.getWriter();
    //拼接xml头
    pw.write("<?xml version='1.0' encoding='UTF-8'?>");
    pw.write("<citys>");
    if ("湖南".equals(province)) {
      pw.write("<city>长沙</city>");
      pw.write("<city>株洲</city>");
      pw.write("<city>湘潭</city>");
      pw.write("<city>岳阳</city>");
    }else if("广东".equals(province)){
      pw.write("<city>广州</city>");
      pw.write("<city>深圳</city>");
      pw.write("<city>中山</city>");
    }
    pw.write("</citys>");
    pw.flush();
    pw.close();
  }
}

运行结果如下:


  分享到:  
0.2700s