ajax做省市联动

时间:2021-07-28 17:09:19

原理:

 当select.jsp页面打开时,向服务器发送异步请求,得到所有省份的名称(文本数据)。然后使用每个省份名称创建<option>,添加到<select name=”province”>中。

  并且为<select name=”province”>元素添加onchange事件监听。当选择的省份发生变化时,再向服务器发送异常请求,得到当前选中的省份下所有城市(XML数据)。然后客户端解析XML文档,使用每个城市名称创建<option>,添加到<select name=”city”>元素中。

代码实现:

前端页面

Web04\WebContent\ajax\select.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'ajax5.jsp' starting page</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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
function createXMLHttpRequest() {
try {
return new XMLHttpRequest();//大多数浏览器
} catch (e) {
try {
return ActvieXObject("Msxml2.XMLHTTP");//IE6.0
} catch (e) {
try {
return ActvieXObject("Microsoft.XMLHTTP");//IE5.5及更早版本
} catch (e) {
alert("浏览器不支持");
throw e;
}
}
}
}
/*
* 1. 在文档加载完毕时发送请求,得到所有省份名称,显示在<select name="province"/>中
* 2. 在选择了新的省份时,发送请求(参数为省名称),得到xml文档,即<province>元素
* 解析xml文档,得到其中所有的<city>,再得到每个<city>元素的内容,即市名,使用市名生成<option>,插入到<select name="city">元素中
*/ window.onload = function() {
/*
ajax四步,请求ProvinceServlet,得到所有省份名称
使用每个省份名称创建一个<option>元素,添加到<select name="province">中
*/
var xmlHttp = createXMLHttpRequest();
xmlHttp.open("GET", "/Web04/ProvinceServlet", true);
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
// 获取服务器的响应
var text = xmlHttp.responseText;
// 使用逗号分隔它,得到数组
var arr = text.split(",");
// 循环遍历每个省份名称,每个名称生成一个option对象,添加到<select>中
for(var i = 0; i < arr.length; i++) {
var op = document.createElement("option");//创建一个指名名称元素
op.value = arr[i];//设置op的实际值为当前的省份名称
var textNode = document.createTextNode(arr[i]);//创建文本节点
op.appendChild(textNode);//把文本子节点添加到op元素中,指定其显示值 document.getElementById("p").appendChild(op);
}
}
}; /*
第二件事情:给<select name="province">添加改变监听
使用选择的省份名称请求CityServlet,得到<province>元素(xml元素)!!!
获取<province>元素中所有的<city>元素,遍历之!获取每个<city>的文本内容,即市名称
使用每个市名称创建<option>元素添加到<select name="city">
*/
var proSelect = document.getElementById("p");
proSelect.onchange = function() {
var xmlHttp = createXMLHttpRequest();
xmlHttp.open("POST", "/Web04/CityServlet", true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send("pname=" + proSelect.value);//把下拉列表中选择的值发送给服务器!
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
/*
把select中的所有option移除(除了请选择)
*/
var citySelect = document.getElementById("c");
// 获取其所有子元素
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>省市联动</h1>
<select name="province" id="p">
<option>===请选择省===</option>
</select>
   
<select name="city" id="c">
<option>===请选择市===</option>
</select>
</body>
</html>

  

处理省份的servlet

Web04\src\ajax\ProvinceServlet.java

package ajax;

import java.io.IOException;
import java.io.InputStream;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader; /**
* Servlet implementation class ProvinceServlet
*/
@WebServlet("/ProvinceServlet")
public class ProvinceServlet extends HttpServlet {
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
try {
//创建解析器对象
SAXReader reader = new SAXReader();
//得到输入流
InputStream input = this.getClass().getResourceAsStream("/china.xml");
//得到document对象
Document doc = reader.read(input);
//查询所有的province的name属性,//province表示无限深度查询,/表示子节点
List<Attribute> arrList = doc.selectNodes("//province/@name");
//将所有的省份名称用逗号连接起来
StringBuilder sb = new StringBuilder();
for(int i=0;i<arrList.size();i++){
sb.append(arrList.get(i).getValue());
if(i<arrList.size()-1){
sb.append(",");
}
}
response.getWriter().print(sb);
} catch (DocumentException e) {
throw new RuntimeException();
} } }

  

处理市数据的servlet

Web04\src\ajax\CityServlet.java

package ajax;

import java.io.IOException;
import java.io.InputStream; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader; /**
* Servlet implementation class CityServlet
*/
@WebServlet("/CityServlet")
public class CityServlet extends HttpServlet {
private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { request.setCharacterEncoding("utf-8");
//注意:发送xml这里要修改!!!
response.setContentType("text/xml;charset=utf-8");
try {
//创建解析器对象
SAXReader reader = new SAXReader();
//得到输入流
InputStream input = this.getClass().getResourceAsStream("/china.xml");
//得到document对象
Document doc = reader.read(input);
//得到省份名称
String pname = request.getParameter("pname");
Element proEle = (Element) doc.selectSingleNode("//province[@name='" + pname + "']");
//把元素转换成字符串
String xmlStr = proEle.asXML();
response.getWriter().print(xmlStr);
} catch (Exception e) {
throw new RuntimeException();
}
} }

  

Web04\src\china.xml

<?xml version="1.0" encoding="utf-8"?>
<china>
<province name="北京">
<city>东城区</city>
<city>西城区</city>
<city>崇文区</city>
<city>宣武区</city>
<city>朝阳区</city>
<city>丰台区</city>
<city>石景山区</city>
<city>海淀区</city>
<city>门头沟区</city>
<city>房山区</city>
<city>通州区</city>
<city>顺义区</city>
<city>昌平区</city>
<city>大兴区</city>
<city>怀柔区</city>
<city>平谷区</city>
<city>密云县</city>
<city>延庆县</city>
</province>
<province name="天津">
<city>和平区</city>
<city>河东区</city>
<city>河西区</city>
<city>南开区</city>
<city>河北区</city>
<city>红桥区</city>
<city>塘沽区</city>
<city>汉沽区</city>
<city>大港区</city>
<city>东丽区</city>
<city>西青区</city>
<city>津南区</city>
<city>北辰区</city>
<city>武清区</city>
<city>宝坻区</city>
<city>宁河县</city>
<city>静海县</city>
<city>蓟县</city>
</province>
<province name="河北">
<city>石家庄</city>
<city>唐山</city>
<city>秦皇岛</city>
<city>邯郸</city>
<city>邢台</city>
<city>保定</city>
<city>张家口</city>
<city>承德</city>
<city>沧州</city>
<city>廊坊</city>
<city>衡水</city>
</province>
<province name="山西">
<city>太原</city>
<city>大同</city>
<city>阳泉</city>
<city>长治</city>
<city>晋城</city>
<city>朔州</city>
<city>晋中</city>
<city>运城</city>
<city>忻州</city>
<city>临汾</city>
<city>吕梁</city>
</province>
<province name="内蒙古">
<city>呼和浩特</city>
<city>包头</city>
<city>乌海</city>
<city>赤峰</city>
<city>通辽</city>
<city>鄂尔多斯</city>
<city>呼伦贝尔</city>
<city>巴彦淖尔</city>
<city>乌兰察布</city>
<city>兴安盟</city>
<city>锡林郭勒盟</city>
<city>阿拉善盟</city>
</province>
<province name="辽宁">
<city>沈阳</city>
<city>大连</city>
<city>鞍山</city>
<city>抚顺</city>
<city>本溪</city>
<city>丹东</city>
<city>锦州</city>
<city>营口</city>
<city>阜新</city>
<city>辽阳</city>
<city>盘锦</city>
<city>铁岭</city>
<city>朝阳</city>
<city>葫芦岛</city>
</province>
<province name="吉林">
<city>长春</city>
<city>吉林</city>
<city>四平</city>
<city>辽源</city>
<city>通化</city>
<city>白山</city>
<city>*</city>
<city>白城</city>
<city>延边</city>
</province>
<province name="黑龙江">
<city>哈尔滨</city>
<city>齐齐哈尔</city>
<city>鸡西</city>
<city>鹤岗</city>
<city>双鸭山</city>
<city>大庆</city>
<city>伊春</city>
<city>佳木斯</city>
<city>七台河</city>
<city>牡丹江</city>
<city>黑河</city>
<city>绥化</city>
<city>大兴安岭</city>
</province>
<province name="上海">
<city>黄浦区</city>
<city>卢湾区</city>
<city>徐汇区</city>
<city>长宁区</city>
<city>静安区</city>
<city>普陀区</city>
<city>闸北区</city>
<city>虹口区</city>
<city>杨浦区</city>
<city>闵行区</city>
<city>宝山区</city>
<city>嘉定区</city>
<city>浦东新区</city>
<city>金山区</city>
<city>松江区</city>
<city>青浦区</city>
<city>南汇区</city>
<city>奉贤区</city>
<city>崇明县</city>
</province>
<province name="江苏">
<city>南京</city>
<city>无锡</city>
<city>徐州</city>
<city>常州</city>
<city>苏州</city>
<city>南通</city>
<city>连云港</city>
<city>淮安</city>
<city>盐城</city>
<city>扬州</city>
<city>镇江</city>
<city>泰州</city>
<city>宿迁</city>
</province>
<province name="浙江">
<city>杭州</city>
<city>宁波</city>
<city>温州</city>
<city>嘉兴</city>
<city>湖州</city>
<city>绍兴</city>
<city>金华</city>
<city>衢州</city>
<city>舟山</city>
<city>台州</city>
<city>丽水</city>
</province>
<province name="安徽">
<city>合肥</city>
<city>芜湖</city>
<city>蚌埠</city>
<city>淮南</city>
<city>马鞍山</city>
<city>淮北</city>
<city>铜陵</city>
<city>安庆</city>
<city>黄山</city>
<city>滁州</city>
<city>阜阳</city>
<city>宿州</city>
<city>巢湖</city>
<city>六安</city>
<city>亳州</city>
<city>池州</city>
<city>宣城</city>
</province>
<province name="福建">
<city>福州</city>
<city>厦门</city>
<city>莆田</city>
<city>三明</city>
<city>泉州</city>
<city>漳州</city>
<city>南平</city>
<city>龙岩</city>
<city>宁德</city>
</province>
<province name="江西">
<city>南昌</city>
<city>景德镇</city>
<city>萍乡</city>
<city>九江</city>
<city>新余</city>
<city>鹰潭</city>
<city>赣州</city>
<city>吉安</city>
<city>宜春</city>
<city>抚州</city>
<city>上饶</city>
</province>
<province name="山东">
<city>济南</city>
<city>青岛</city>
<city>淄博</city>
<city>枣庄</city>
<city>东营</city>
<city>烟台</city>
<city>潍坊</city>
<city>济宁</city>
<city>泰安</city>
<city>威海</city>
<city>日照</city>
<city>莱芜</city>
<city>临沂</city>
<city>德州</city>
<city>聊城</city>
<city>滨州</city>
<city>荷泽</city>
</province>
<province name="河南">
<city>郑州</city>
<city>开封</city>
<city>洛阳</city>
<city>平顶山</city>
<city>安阳</city>
<city>鹤壁</city>
<city>新乡</city>
<city>焦作</city>
<city>濮阳</city>
<city>许昌</city>
<city>漯河</city>
<city>三门峡</city>
<city>南阳</city>
<city>商丘</city>
<city>信阳</city>
<city>周口</city>
<city>驻马店</city>
</province>
<province name="湖北">
<city>武汉</city>
<city>黄石</city>
<city>十堰</city>
<city>宜昌</city>
<city>襄樊</city>
<city>鄂州</city>
<city>荆门</city>
<city>孝感</city>
<city>荆州</city>
<city>黄冈</city>
<city>咸宁</city>
<city>随州</city>
<city>恩施</city>
<city>神农架</city>
</province>
<province name="湖南">
<city>长沙</city>
<city>株洲</city>
<city>湘潭</city>
<city>衡阳</city>
<city>邵阳</city>
<city>岳阳</city>
<city>常德</city>
<city>张家界</city>
<city>益阳</city>
<city>郴州</city>
<city>永州</city>
<city>怀化</city>
<city>娄底</city>
<city>湘西</city>
</province>
<province name="广东">
<city>广州</city>
<city>韶关</city>
<city>深圳</city>
<city>珠海</city>
<city>汕头</city>
<city>佛山</city>
<city>江门</city>
<city>湛江</city>
<city>茂名</city>
<city>肇庆</city>
<city>惠州</city>
<city>梅州</city>
<city>汕尾</city>
<city>河源</city>
<city>阳江</city>
<city>清远</city>
<city>东莞</city>
<city>中山</city>
<city>潮州</city>
<city>揭阳</city>
<city>云浮</city>
</province>
<province name="广西">
<city>南宁</city>
<city>柳州</city>
<city>桂林</city>
<city>梧州</city>
<city>北海</city>
<city>防城港</city>
<city>钦州</city>
<city>贵港</city>
<city>玉林</city>
<city>百色</city>
<city>贺州</city>
<city>河池</city>
<city>来宾</city>
<city>崇左</city>
</province>
<province name="海南">
<city>海口</city>
<city>三亚</city>
</province>
<province name="重庆">
<city>重庆</city>
<city>万州区</city>
<city>涪陵区</city>
<city>渝中区</city>
<city>大渡口区</city>
<city>江北区</city>
<city>沙坪坝区</city>
<city>九龙坡区</city>
<city>南岸区</city>
<city>北碚区</city>
<city>万盛区</city>
<city>双桥区</city>
<city>渝北区</city>
<city>巴南区</city>
<city>黔江区</city>
<city>长寿区</city>
<city>綦江县</city>
<city>潼南县</city>
<city>铜梁县</city>
<city>大足县</city>
<city>荣昌县</city>
<city>璧山县</city>
<city>梁平县</city>
<city>城口县</city>
<city>丰都县</city>
<city>垫江县</city>
<city>武隆县</city>
<city>忠县</city>
<city>开县</city>
<city>云阳县</city>
<city>奉节县</city>
<city>巫山县</city>
<city>巫溪县</city>
<city>石柱土家族自治县</city>
<city>秀山土家族苗族自治县</city>
<city>酉阳土家族苗族自治县</city>
<city>彭水苗族土家族自治县</city>
<city>江津</city>
<city>合川</city>
<city>永川</city>
<city>南川</city>
</province>
<province name="四川">
<city>成都</city>
<city>自贡</city>
<city>攀枝花</city>
<city>泸州</city>
<city>德阳</city>
<city>绵阳</city>
<city>广元</city>
<city>遂宁</city>
<city>内江</city>
<city>乐山</city>
<city>南充</city>
<city>眉山</city>
<city>宜宾</city>
<city>广安</city>
<city>达州</city>
<city>雅安</city>
<city>巴中</city>
<city>资阳</city>
<city>阿坝</city>
<city>甘孜</city>
<city>凉山</city>
</province>
<province name="贵州">
<city>贵阳</city>
<city>六盘水</city>
<city>遵义</city>
<city>安顺</city>
<city>铜仁</city>
<city>黔西南</city>
<city>毕节</city>
<city>黔东南</city>
<city>黔南</city>
</province>
<province name="云南">
<city>昆明</city>
<city>曲靖</city>
<city>玉溪</city>
<city>保山</city>
<city>昭通</city>
<city>丽江</city>
<city>思茅</city>
<city>临沧</city>
<city>楚雄</city>
<city>红河</city>
<city>文山</city>
<city>西双版纳</city>
<city>大理</city>
<city>德宏</city>
<city>怒江</city>
<city>迪庆</city>
</province>
<province name="*">
<city>拉萨</city>
<city>昌都</city>
<city>山南</city>
<city>日喀则</city>
<city>那曲</city>
<city>阿里</city>
<city>林芝</city>
</province>
<province name="陕西">
<city>西安</city>
<city>铜川</city>
<city>宝鸡</city>
<city>咸阳</city>
<city>渭南</city>
<city>延安</city>
<city>汉中</city>
<city>榆林</city>
<city>安康</city>
<city>商洛</city>
</province>
<province name="甘肃">
<city>兰州</city>
<city>嘉峪关</city>
<city>金昌</city>
<city>白银</city>
<city>天水</city>
<city>武威</city>
<city>张掖</city>
<city>平凉</city>
<city>酒泉</city>
<city>庆阳</city>
<city>定西</city>
<city>陇南</city>
<city>临夏</city>
<city>甘南</city>
</province>
<province name="青海">
<city>西宁</city>
<city>海东</city>
<city>海北</city>
<city>黄南</city>
<city>海南</city>
<city>果洛</city>
<city>玉树</city>
<city>海西</city>
</province>
<province name="宁夏">
<city>银川</city>
<city>石嘴山</city>
<city>吴忠</city>
<city>固原</city>
<city>中卫</city>
</province>
<province name="*">
<city>乌鲁木齐</city>
<city>克拉玛依</city>
<city>吐鲁番</city>
<city>哈密</city>
<city>昌吉</city>
<city>博尔塔拉</city>
<city>巴音郭楞</city>
<city>阿克苏</city>
<city>克孜勒苏</city>
<city>喀什</city>
<city>和田</city>
<city>伊犁</city>
<city>塔城</city>
<city>阿勒泰</city>
<city>石河子</city>
<city>阿拉尔</city>
<city>图木舒克</city>
<city>五家渠</city>
</province>
<province name="香港">
<city>香港</city>
</province>
<province name="澳门">
<city>澳门</city>
</province>
<province name="*">
<city>*</city>
</province>
</china>

  

效果:

ajax做省市联动

选择一个省份,弹出市级列表

ajax做省市联动