Fork me on GitHub

练习: 省市联动(Ajax)

// 示例一:
  china.xml  (位于 src 目录下)
    <?xml version="1.0" encoding="utf-8"?>
    <china>
        <province name="北京">
            <city>东城区</city>
            <city>西城区</city>
            <city>宣武区</city>
            <city>大兴区</city>
        </province>
        <province name="天津">
            <city>河东区</city>
            <city>河西区</city>
            <city>南开区</city>
            <city>大港区</city>
        </province>
    </china>

// Servlet
    // ProvinceServlet
    public class ProvinceSerlvet extends HttpServlet{

        public void doGet(HttpServletRequest request,HttpServletResponse response)
                throws ServletException, IOException{

            // 处理编码问题
            response.setContentType("text/html;charset=utf-8");

            try{
                // 解析 xml 文档
                XMLReader reader = new XMLReader();

                // 获取 xml 文档的输入流
                InputStream input = this.getClass().getResourceAsStream("/china.xml");

                Document doc = reader.read(input);

                // 使用 XPath ,获取文档中 province 元素
                List<Attribute> attrList = doc.selectNodes("//province/@name");


                // 遍历集合,获取 province 元素中 name 属性的值
                // 并保存到 StringBuilder 中
                StringBuilder sb = new StringBuilder();

                for(int i=0; i<attrList.size(); i++){
                    sb.append(attrList.get(i).getValue());
                    if(i < arrList.size() - 1){
                        sb.append(",");
                    }
                }

                // 响应
                response.getWriter().print(sb);
            }catch(Exception e){
                throw new RuntimeException(e);
            }
        }
    }

    // CityServlet
    public class CityServlet extends HttpServlet{
        public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/xml;charset=utf-8");

            try{
                // 解析 xml
                SAXReader reader = new SAXReader();
                InputStream input = this.getClass().getResourceAsStream("/china.xml");

                Document doc = reader.read(input);

                // 获取请求参数
                String pname = request.getParameter("pname");

                // XPath 查询
                Element ele = doc.selectSingleNode("//province/[@name='"+pname+"']");

                // 把元素转换成字符串, org.dom4j.Node
                String xmlStr = ele.asXML();

                // 响应给客户端
                response.getWriter().print(xmlStr);

            } catch(Exception e){
                throw new RuntimeException(e);
            }
        }  
    }

    // index.jsp
    <head>
        <script type="text/javascript">

            // 创建 XMLHttpRequest 对象, 处理浏览器差异
            function createXMLHttpRequest(){
                try{
                    return new XMLHttpRequest();
                } catch(e){
                    try{
                        return new ActiveXObject("Msxml2.XMLHTTP");
                    }catch(e){
                        try{
                            return new ActiveXObject("Microsoft.XMLHTTP");
                        }catch(e){
                            throw e;
                        }
                    }
                }
            }

            // 注册监听器
            window.onload = function(){
                // ajax 四步,请求 ProvinceServlet, 得到所有省份的名称
                // 使用每个省份的名称创建一个 <option> 元素, 添加到 <select name="province"> 中

                var xmlHttp = createXMLHttpRequest();
                xmlHttp.open("GET","<c:url value='/ProvinceServlet'/>",true);
                xmlHttp.send(null);

                xmlHttp.onreadystatechange = function(){
                    if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
                        var text = xmlHttp.responseText;

                        // 将字符串转换成数组
                        var arr = text.split(",");
                        for(var i=0, i<arr.length; i++){
                            // 创建 option 元素, 示例<option value="北京">北京</option>
                            var op = document.creatElement("option");

                            op.value = arr[i];
                            var textNode = document.createTextNode(arr[i]);
                            op.appendChild(textNode);
                            document.getElementById("p").appendChild(op);
                        }
                    }
                };

                // 给 <select name="province"> 添加改变监听器
                // 使用选择的省份名称请求 CityServlet, 得到 <province> 元素(xml元素)!!!
                // 获取 <province> 元素中所有的 city 元素, 遍历之! 获取每个 <city> 的文本内容, 即市名称
                // 使用每个市名称创建 <option> 元素添加到 <select name="city">

                var ele = document.getElementById("p");
                ele.onchange = function(){
                    var xmlHttp = createXMLHttpRequest();
                    xmlHttp.open("POST","<c:url value='/CityServlet'/>",true);
                    xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                    xmlHttp.send("pname="+this.value);

                    xmlHttp.onreadystatechange = function(){
                        if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
                            // 清空 <option name="city"> 原有的内容
                            var citySelect = document.getElementById("c");
                            var optionEleList = citySelect.getElementsByTagName("option");
                            while(optionEleList.length > 1){
                                citySelect.removeChild(optionEleList[i]);
                            }

                            var doc = xmlHttp.responseXML;

                            // 获取所有的 city 元素
                            var cityEleList = doc.getElementsByTagName("city");
                            for(var i=0; i<cityEleList.length; i++){
                                var cityEle = cityEleList[i];
                                var cityName;

                                // 处理浏览器差异
                                if(window.addEventListener){
                                    cityName = cityEle.textContent;
                                } else {
                                    cityName = cityEle.text;
                                }

                                // 添加到 <select name="city"> 元素中
                                var op = document.createElement("op");
                                op.value = cityName;
                                var textNode = document.createTextNode(cityName);
                                op.appendChild(textNode);

                                citySelect.appendChild(op);
                            }
                        }
                    };
                };
            };

        </script>
    </head>
    <body>
        <h1>省市联动</h1>
        <select name="province" id="p">
            <option>===请选择省===</option>
        </select>
        <select name="city" id="c">
            <option>===请选择市===</option>
        </select>
    </body>

// 升级版, JQuery 和 Ajax
    <head>
        <script type="text/javascript" src="<c:url value='/jquery/jquery-3.2.1.min.js'/>"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $.ajax({
                    url:"<c:url value='/ProvinceServlet'/>",
                    success:function(data){
                        var arr = data.split(",");
                        $.each(arr,function(index,value){
                            $("#pv").append($("<option value='"+value+"'>"+value+"</option>"));
                        });
                    }
                });

                // 在 <select name="province"> 上注册事件
                $("#pv").change(function(){
                    $("#c").empty();
                    $.ajax({
                        url:"<c:url value='/CityServlet'/>",
                        data:{pname:$("#pv").val()},
                        type:"POST",
                        success:function(data){
                            $.each($(data).find("city"), function(key,value){
                                $("#c").append(
                   $("<option value='"+value.textContent+"'>"+value.textContent+"</option>"
                                    ));
                            });
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <h1>省市联动</h1>
        <select name="province" id="pv">
            <option>===请选择省===</option>
        </select>
        <select name="city" id="c">
            <option>===请选择市===</option>
        </select>
    </body>


参考资料:

posted @ 2017-10-12 16:26  小a的软件思考  阅读(239)  评论(0编辑  收藏  举报