Ajax实现省份-城市二级下拉联动

基于XML,以POST方式,完成省份-城市二级下拉联动

数据库 mysql,表:t_city

JavaWeb项目,使用servlet

ajax.js
// 创建AJAX异步对象
function createAJAX() {
	var ajax = null;

	if (window.XMLHttpRequest) {
		ajax = new XMLHttpRequest();
	} else {
		// 如果是IE5或IE6,使用 ActiveXObject
		ajax = new ActiveXObject("Microsoft.XMLHTTP");
	}

	return ajax;
}

province.jsp

<%@ page language="java" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
	<title>基于XML,以POST方式,完成省份-城市二级下拉联动</title>
	<script type="text/javascript" src="js/ajax.js"></script>
</head>

<body>

	<select id="provinceId" style="width:120px">
		<option value="0">选择省份</option>
		<option>福建</option>
		<option>广东</option>
	</select>
	  
	<select id="cityId" style="width:120px">
		<option>选择城市</option>
	</select>
	
	<script type="text/javascript">
		// 定位到城市下拉框
		var cityEle = document.getElementById("cityId");
		
		// 定位到省份下拉框,同时添加内容改变事件
		document.getElementById("provinceId").onchange = function(){
			/*
			// 下面的方式可以获取省份名,可是太麻烦了
			// 获取选中option标签的索引值
			var index = this.selectedIndex;
			// 定位选中的option标签
			var optionEle = this[index];
			// 获取option标签中的内容,即省份的名字
			var provinceName = optionEle.innerHTML;
			*/
			// 获取选中省份的名字
			var provinceName = this.value;
			if(provinceName == "0"){
				// 清空城市下拉框中的内容,除了第一项外
				// 方法一
				//cityEle.innerHTML = "<option>选择城市</option>";
				// 方法二(推荐)
				cityEle.options.length = 1;
				return;
			}
			var ajax = createAJAX();
			var url = "${pageContext.request.contextPath}/ProvinceCityServlet?time="+new Date().getTime();
			ajax.open("POST",url);
			ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
			ajax.send("provinceName=" + provinceName);
			
			ajax.onreadystatechange = function(){
				if(ajax.readyState == 4 && ajax.status == 200){
					var cityText = "<option>选择城市</option>";
					// 清空城市下拉框中的内容,除了第一项外
					cityEle.options.length = 1;
					
					// 从服务器返回的xml数据
					var xmlDoc = ajax.responseXML;
					// 按照DOM规则解析xml文档
					var cityEles = xmlDoc.getElementsByTagName("city");
					for(i=0; i<cityEles.length; i++){
						// innerHTML不能获取XML数据源的节点值,下面的方法无法在ie中取到值
						// var city = cityEles[i].cityEles[i].innerHTML;
						// 下面两种方式都可以,推荐后一种
						// var city = cityEles[i].childNodes[0].nodeValue;
						var city = cityEles[i].firstChild.nodeValue;
						// 创建option标签
						var optionEle = document.createElement("option");
						optionEle.innerHTML = city;
						cityEle.appendChild(optionEle);
					}
				}
			};
			
		};
	
	</script>
	
	<!-- 
	<form action="" enctype="application/x-www-form-urlencoded"></form>
 	-->
 	
</body>
</html>
ProvinceCityServlet.java

package cn.javaee.js.province;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 基于XML,以POST方式,完成省份-城市二级下拉联动
 * 
 * @author lzf
 * @version V1.0
 */
public class ProvinceCityServlet extends HttpServlet {

	private static final long serialVersionUID = -3426124869778232040L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		// 通知ajax异步对象,服务器响应的数据是xml格式的
		response.setContentType("text/xml;charset=UTF-8");
		try {
			// 省份名称
			String provinceName = request.getParameter("provinceName");
			// 用来存放xml数据
			StringBuffer sb = new StringBuffer();
			sb.append("<?xml version='1.0' encoding='UTF-8'?>");
			sb.append("<citys>");

			// JDBC连接mysql数据库
			Connection conn = null;
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/hib_demo";
			conn = DriverManager.getConnection(url, "root", "root");

			// 预编译,防注入
			String sql = "select city from t_city where province=? ";
			PreparedStatement stmt = conn.prepareStatement(sql);
			// 注意:这里的index是1而不是0
			stmt.setString(1, provinceName);
			ResultSet rs = stmt.executeQuery();
			while (rs.next()) {
				// 注意:这里的index是1而不是0
				String city = rs.getString(1);
				sb.append("<city>");
				sb.append(city);
				sb.append("</city>");
			}
			sb.append("</citys>");

			// 关闭连接
			rs.close();
			stmt.close();
			conn.close();

			// 输出流
			PrintWriter pw = response.getWriter();
			pw.write(sb.toString());
			// 关闭流
			pw.flush();
			pw.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}




展开阅读全文

没有更多推荐了,返回首页