Ajax下拉菜单联动

8 篇文章 0 订阅
0 篇文章 0 订阅

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" οnchange="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();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值