jsp
主要是要注意多Document的操作
<%-- Created by IntelliJ IDEA. User: YuWenHui Date: 2017/4/23 0023 Time: 19:00 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>省市联动</title> <script> 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 () { 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++){ // 创建一个指定名称的元素 var op =document.createElement("option"); // 设置实际值 op.value=arr[i]; // 创建文本节点 var textNode = document.createTextNode(arr[i]); // 把文本子节点添加到op元素总 op.appendChild(textNode); document.getElementById("province").appendChild(op); } } }; }; var provinceSelect = document.getElementById("province"); provinceSelect.onchange=function () { var xmlHttp = createXMLHttpRequest(); xmlHttp.open("POST","<c:url value='/CityServletServlet'/>",true); xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlHttp.send("pname="+provinceSelect.value); xmlHttp.onreadystatechange=function () { if(xmlHttp.readyState==4 && xmlHttp.status==200){ // 把select中的所有option移除(除了请选择) var citySelect = document.getElementById("city"); // 获取其所有子元素 var optionEleList = citySelect.getElementsByTagName("option"); // 循环遍历每个option元素,然后在citySelect中移除 while(optionEleList.length > 1) {//子元素的个数如果大于1就循环,等于1就不循环了! citySelect.removeChild(optionEleList[1]);//总是删除1下标,因为1删除了,2就变成1了! } var doc = xmlHttp.responseXML; // 得到所有名为city的元素 var cityEleList = doc.getElementsByTagName("city"); // 循环遍历每个city元素 for(var i = 0; i < cityEleList.length; i++) { var cityEle = cityEleList[i];//得到每个city元素 var cityName; // 获取市名称 if(window.addEventListener) {//处理浏览器的差异 cityName = cityEle.textContent;//支持FireFox等浏览器 } else { cityName = cityEle.text;//支持IE } // 使用市名称创建option元素,添加到<select name="city">中 var op = document.createElement("option"); op.value = cityName; // 创建文本节点 var textNode = document.createTextNode(cityName); op.appendChild(textNode);//把文本节点追加到op元素中 //把op添加到<select>元素中 citySelect.appendChild(op); } }; } </script> </head> <body> <h1>省市联动AJAX</h1> <select name="province" id="province"> <option>请选择省份</option> </select><br> <select name="city" id="city"> <option>请选择市</option> </select> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>ValidateUsernameServlet</servlet-name> <servlet-class>servlet.ValidateUsernameServlet</servlet-class> </servlet> <servlet> <servlet-name>ProvinceServlet</servlet-name> <servlet-class>servlet.ProvinceServlet</servlet-class> </servlet> <servlet> <servlet-name>CityServlet</servlet-name> <servlet-class>servlet.CityServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CityServlet</servlet-name> <url-pattern>/CityServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ProvinceServlet</servlet-name> <url-pattern>/ProvinceServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ValidateUsernameServlet</servlet-name> <url-pattern>/ValidateUsernameServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
servlet
provinceServlet
package servlet; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * Created by YuWenHui on 2017/4/23 0023. */ public class ProvinceServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); // 得到Document对象 // 创建解析器对象,通过该解析器的读方法,传递一个流对象,从而得到一个Document对象 SAXReader reader = new SAXReader(); InputStream inputStream = this.getClass().getResourceAsStream("/china.xml"); try { Document document = reader.read(inputStream); List<Attribute> list = document.selectNodes("//province/@name"); StringBuilder stringBuilder = new StringBuilder(); for (int i=0;i<list.size();i++){ stringBuilder.append(list.get(i).getValue()); if (i<list.size()-1){ stringBuilder.append(","); } } response.getWriter().print(stringBuilder); } catch (DocumentException e) { throw new RuntimeException(e); } } }
cityServlet
package servlet; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; /** * Created by YuWenHui on 2017/4/23 0023. */ public class CityServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/xml;charset=utf-8"); SAXReader reader = new SAXReader(); InputStream inputStream = this.getClass().getResourceAsStream("/chain.xml"); try { Document document = reader.read(inputStream); String pname = request.getParameter("pname"); Element element = (Element) document.selectSingleNode("//province[@name='"+pname+"']"); String xmlString = element.asXML(); response.getWriter().print(xmlString); } catch (Exception e) { throw new RuntimeException(e); } } }