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

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

<%@ 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%>">
    <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操作

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();
	}
}

运行结果如下:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值