1. 程式人生 > >Ajax下拉選單聯動

Ajax下拉選單聯動

AJAX = Asynchronous + Javascript + xml

簡直TMD是藝術

demo.html

<html>
	<head>
		<title>Ajax下拉列表</title>
		<meta charset="utf-8"/>
		<script>
			function getXhr() {
				var xhr = null;
				if(window.XMLHttpRequest) {
					xhr = new XMLHttpRequest();
				} else {
					xhr = new ActiveXObject("Microsoft.XMLHttp");
				}
				return xhr;
			}
			
			function change(province) {
				var cities = document.getElementById("cities");
				var xhr = getXhr();
				xhr.open("post", "getmenu.do");
				xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
				xhr.onreadystatechange = function() {
					if(xhr.readyState==4 && xhr.status==200) {
						var cities = xhr.responseText.split(",");
						var citiesNode = document.getElementById("cities");
						citiesNode.innerHTML = "";
						//console.log(cities);
						for(var city in cities) {
							var option = document.createElement("option");
							option.innerHTML = cities[city];
							citiesNode.appendChild(option);
						}
					}
				};
				xhr.send("province="+province);
				var citiesNode = document.getElementById("cities");
				
			}
			
		</script>
	</head>
	<body>
	省份:<select id="provinces" onchange="change(this.value);">
			<option value="sd">山東</option>
			<option value="js">江蘇</option>
			<option value="hb">河北</option>
		</select>
	城市:<select id="cities"></select>
	</body>
</html>

MenuServlet.java

package servlet;
import java.io.IOException;
import java.io.PrintWriter;

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


public class MenuServlet extends HttpServlet {

	@Override
	protected void service(
			HttpServletRequest req, 
			HttpServletResponse res)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		res.setContentType("text/html;charset=utf-8");
		PrintWriter out = res.getWriter();
		String province = req.getParameter("province");
		if("sd".equals(province)) {
			out.print("濟南,青島,泰安");
		} else if("js".equals(province)) {
			out.print("南京,蘇州,無錫");
		} else if("hb".equals(province)) {
			out.print("石家莊,唐山,秦皇島");
		}
		out.flush();
		out.close();
	}

}