使用ajax+json+struts实现省份下拉框二级联动

前端之家收集整理的这篇文章主要介绍了使用ajax+json+struts实现省份下拉框二级联动前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

前台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 'provincecityarea.jsp' starting page</title>
</head>

<body>
	<select id="provinceID" style="width:150px">
		<option>选择省份</option>
		<option>河南</option>
		<option>上海</option>
		<option>杭州</option>
	</select>

	<select id="cityID" style="width:150px">
		<option>选择城市</option>
	</select>

	<select id="areaID" style="width:150px">
		<option>选择区域</option>
	</select>
</body>
<!--
     	省份>城市
     -->
<script type="text/javascript">
	document.getElementById("provinceID").onchange = function() {
		//清空城市下拉框
		var cityEle = document.getElementById("cityID");
		cityEle.options.length = 1;
		//清空区域下拉框
		var areaEle = document.getElementById("areaID");
		areaEle.options.length = 1;
		//定位到当前所选的值
		var pro = this[this.selectedIndex].innerHTML;
		//如果选择了城市,开始触发ajax
		if ("选择省份" != pro) {
			var ajax = createAjax(); //创建ajax对象
			function createAjax() {
				var a = null;
				try {
					a = new ActiveXObject("microsoft.xmlhttp");
				} catch (e) {
					a = new XMLHttpRequest();
				}
				return a;
			}
			//设置参数
			var method = "POST";
			var url = "${pageContext.request.contextPath}/findCityByProvinceRequest?time="
					+ new Date().getTime();
			//准备请求
			ajax.open(method,url);
			//设置请求头
			ajax.setRequestHeader("content-type","application/x-www-form-urlencoded")
			var content = "bean.province=" + pro;
			//向服务器发送
			ajax.send(content);
			//监听状态
			ajax.onreadystatechange = function() {
				if (ajax.readyState == 4) {
					if (ajax.status == 200) {
						//返回JAVA格式的JSON文本
						var jsonJAVA = ajax.responseText;

						//p所代表的是java格式的json文本,是不能直接被js执行的
						//解决方案:将java格式的json文本,转成js格式的json文本
						//如何做:用js提供的一个函数搞定
						var jsonJS = eval("(" + jsonJAVA + ")");
						//取城市数组
						var array = jsonJS.cityList;
						var size = array.length;
						//遍历
						for ( var i = 0; i < size; i++) {
							var city = array[i];
							//创建一个option节点,内容为城市数组的值
							var option = document.createElement("option");
							option.innerHTML = city;
							//把option节点添加到select节点里面,即城市节点里面添加城市名
							cityEle.appendChild(option);
						}
					}
				}
			}
		}
	}
</script>
<!-- 城市->区域 -->
<script type="text/javascript">
	document.getElementById("cityID").onchange = function() {
		var areaElement = document.getElementById("areaID");
		areaElement.options.length = 1;
		var city = this[this.selectedIndex].innerHTML;
		if ("选择城市" != city) {
			//NO1)
			var ajax = createAjax();
			function createAjax() {
				var a = null;
				try {
					a = new ActiveXObject("microsoft.xmlhttp");
				} catch (e) {
					a = new XMLHttpRequest();
				}
				return a;
			}
			//NO2)
			var method = "POST";
			var url = "${pageContext.request.contextPath}/findAreaByCityRequest?time="
					+ new Date().getTime();
			ajax.open(method,url);
			//NO3)
			ajax.setRequestHeader("content-type","application/x-www-form-urlencoded")
			//NO4)
			var content = "bean.city=" + city;
			ajax.send(content);

			//------------------------------------------等待

			//NO5)
			ajax.onreadystatechange = function() {

				if (ajax.readyState == 4) {
					if (ajax.status == 200) {
						//NO6)
						var jsonJAVA = ajax.responseText;
						var jsonJS = eval("(" + jsonJAVA + ")");
						var array = jsonJS.areaList;
						var size = array.length;
						for ( var i = 0; i < size; i++) {
							var area = array[i];
							var option = document.createElement("option");
							option.innerHTML = area;
							areaElement.appendChild(option);
						}
					}
				}
			}

		}
	}
</script>

</html>

城市和省份封装JavaBean

public class Bean {

	private String province;// 省份
	private String city;// 城市

	public Bean() {
	}

	public String getProvince() {
		return province;
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

}

struts的action处理

public class ProvinceCityAreaAction extends ActionSupport {
	//封装对象属性,使用模型驱动的话需实现模型驱动接口,新建对象并私有,重写getModel()对象
	private Bean bean;

	public Bean getBean() {
		return bean;
	}

	public void setBean(Bean bean) {
		this.bean = bean;
	}

	/**
	 * 根据省份获取城市
	 */
	public String findCityByProvince() throws Exception {
		cityList = new ArrayList<String>();
		if ("上海".equals(bean.getProvince())) {
			cityList.add("闵行");
			cityList.add("浦东");
		} else if ("河南".equals(bean.getProvince())) {
			cityList.add("洛阳");
			cityList.add("郑州");
			cityList.add("焦作");
		} else if ("杭州".equals(bean.getProvince())) {
			cityList.add("余杭");
			cityList.add("江干");
			cityList.add("西湖");
			cityList.add("萧山");
		}
		// 让struts2框架帮你将List/Set/Map<String>转成JSON文本
		return SUCCESS;
	}

	/**
	 * 根据城市获取区域
	 */
	public String findAreaByCity() throws Exception {
		areaList = new ArrayList<String>();
		if ("洛阳".equals(bean.getCity())) {
			areaList.add("AA");
			areaList.add("BB");
		} else if ("闵行".equals(bean.getCity())) {
			areaList.add("CC");
			areaList.add("DD");
			;
		} else if ("西湖".equals(bean.getCity())) {
			areaList.add("EE");
			areaList.add("FF");
		} else if ("郑州".equals(bean.getCity())) {
			areaList.add("GG");
			areaList.add("HH");
		}
		return SUCCESS;
	}

	private List<String> areaList;// 区域的集合
	private List<String> cityList;// 城市的集合

	public List<String> getCityList() {
		return cityList;
	}

	public List<String> getAreaList() {
		return areaList;
	}
}

struts.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<package name="myPackage" extends="json-default" namespace="/">
	<!-- 全局结果类型 -->
		<global-results>
			<result name="success" type="json"/>
		</global-results>
		
		<action name="checkRequest" class="action.CheckcodeAction"
			method="check">
		</action>
		<!-- 省份->城市 -->
		<action 
			name="findCityByProvinceRequest" 
			class="provincecityarea.ProvinceCityAreaAction" 
			method="findCityByProvince">
		</action>
		
		
		<!-- 城市->区域 -->
		<action 
			name="findAreaByCityRequest" 
			class="provincecityarea.ProvinceCityAreaAction" 
			method="findAreaByCity">
		</action>
		
	</package>
</struts>
原文链接:https://www.f2er.com/ajax/160507.html

猜你在找的Ajax相关文章