1. 程式人生 > >ajax實現省市聯動

ajax實現省市聯動

jsp頁面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
	$(function(){
		//頁面載入成功查詢所有的省
		$.get(
			"${pageContext.request.contextPath}/selectPro",
			function(d){
				var $pro=$("#proid");
				$(d).each(function(){
					$pro.append("<option value="+this.provinceid+">"+this.name+"</option>");
					
				});
			},
			"json"
		);
		//給省份下拉選派發change事件
		$("#proid").change(function(){
			//獲取省份id
			var $pid = $(this).val();
			alert($pid);
			//傳送ajax請求,查詢所有的市 
			$.get(
					"/pro-city/selectCity",
					{"pid":$pid},
					function(d){
						alert(d);
						var $city = $("#cityid");
						//初始化
						$city.html("--請選擇--");
						$(d).each(function(){
							//alert(this.name);
							
							$city.append("<option value="+this.cityid+">"+this.name+"</option>");
							
						});
					},
					"json"
					
					
			
			);
			
		});
	})
</script>
<title>省市聯動</title>
</head>
<body>
	<select id="proid" name="province">
		<option>--省份--</option>
	</select>
	<select id="cityid" name="city">
		<option>--請選擇--</option>
	</select>
</body>
</html>

servlet、service、dao還是那一套流程,這裡就省略了