1. 程式人生 > >初學ajax,實現使用者名稱重複提示、二級/三級聯動下拉框

初學ajax,實現使用者名稱重複提示、二級/三級聯動下拉框

初學ajax,實現非同步操作!

               

以下為三級聯動下拉框部分程式碼

jsp頁面部分程式碼

<table>
   			<tr>
   				<th>下拉框:</th>
	   			<td>
				   	<select id="provinceId" name="provinceId">
				   		<option>請選擇省份</option>
						   <c:forEach var="list" items="${allProvinces}" varStatus="vs">
						  		<option value="${list.id }">${list.name }</option><!-- 將對應的id傳到後臺 -->
						   </c:forEach>
				   	</select>
			   		    
			   		<select id="cityId" name="cityId">
			   			<option>請選擇城市</option>
			   		</select>
			   		    
			   		<select id="countyId" name="countyId">
			   			<option>請選擇縣區</option>
			   		</select>
			   		    
		   		</td>
				<td><input type="submit" value="submit"></td>
	   		</tr>
   		</table>
<script type="text/javascript">
   		
   		document.getElementById("provinceId").onchange = function(){
   			//清空城市下拉框中的內容,除第一項
   			var cityElement = document.getElementById("cityId");
   			cityElement.options.length = 1;
   			//清空縣下拉框中的內容,除第一項
   			var countyElement = document.getElementById("countyId");
   			countyElement.options.length = 1;
   			
   			//獲取選中option標籤的索引號,從0開始
   			var index = this.selectedIndex;
			var optionElement = this[index];
			
			var provinceId = optionElement.getAttribute("value");//根據屬性獲取value的值 ,即id--${list.id }
			//alert(provinceId)
			provinceId = Number(provinceId);//將string轉為number
			//alert(typeof provinceId)
			/* 
			//獲取選中的option標籤中的內容
			var province = optionElement.innerHTML;
			alert(province) 
			*/
			
			if( 0 != provinceId){
				var ajax = createAJAX();
				//alert(ajax!=null)
				var method = "POST";
				var url = "${pageContext.request.contextPath}/ProvinceCityCountyServlet?method=ajaxone&time="+new Date().getTime();
				ajax.open(method, url);
				ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
				var content = "provinceId="+provinceId;
				ajax.send(content);
				
				
				ajax.onreadystatechange = function(){
					if(ajax.readyState == 4){
						if(ajax.status == 200){
							var xmlDocument = ajax.responseXML;
							var cityElementArray = xmlDocument.getElementsByTagName("city");
							var size = cityElementArray.length;
							for(var i=0; i<size;i++){
							
								var city = cityElementArray[i].firstChild.nodeValue;
								
								var optionElement = document.createElement("option");	     //建立標籤
								var cityIdvalue = cityElementArray[i].getAttribute("value"); //cityIdValue是該下來框所對應的id值
								optionElement.setAttribute("value", cityIdvalue); 			 //給該標籤建立屬性
								
								optionElement.innerHTML = city;
								cityElement.appendChild(optionElement);
							}
						}
					}
				}
			}
   		}
   	</script>
<script type="text/javascript">
   		document.getElementById("cityId").onchange = function(){
   			//清空縣的下拉框中的內容,除第一項
   			var countyElement = document.getElementById("countyId");
   			countyElement.options.length = 1;
   			
   			//獲取選中option標籤的索引號,從0開始
   			var index = this.selectedIndex;
			var optionElement = this[index];
			
			var cityId = optionElement.getAttribute("value");//根據屬性獲取value的值 ,即id--${list.id }
			//alert(cityId)
			cityId = Number(cityId);//將string轉為number
			
			if( 0 != cityId){
				var ajax = createAJAX();
				//alert(ajax!=null)
				var method = "POST";
				var url = "${pageContext.request.contextPath}/ProvinceCityCountyServlet?method=ajaxtwo&time="+new Date().getTime();
				ajax.open(method, url);
				ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
				var content = "cityId="+cityId;
				ajax.send(content);
				
				ajax.onreadystatechange = function(){
					if(ajax.readyState == 4){
						if(ajax.status == 200){
							var xmlDocument = ajax.responseXML;
							var countyElementArray = xmlDocument.getElementsByTagName("county");
							var size = countyElementArray.length;
							for(var i=0; i<size;i++){
								var county = countyElementArray[i].firstChild.nodeValue;
								var optionElement = document.createElement("option");	//建立標籤
								
								var countyIdvalue = countyElementArray[i].getAttribute("value"); //cityIdValue是該下來框所對應的id值
								//alert(countyIdvalue)
								optionElement.setAttribute("value", countyIdvalue); //給該標籤建立屬性
								
								optionElement.innerHTML = county;
								//alert('hello')
								countyElement.appendChild(optionElement);
							}
						}
					}
				}
			}
   		}
   	</script>
servlet程式碼
@WebServlet("/ProvinceCityCountyServlet")
public class ProvinceCityCountyServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String method = request.getParameter("method");
		
		if(method.equals("ajaxone")){
			
			response.setContentType("text/xml;charset=utf-8");
			String provinceId = request.getParameter("provinceId");
			
			CityService cityService = new CityService();
			List<City> allCities = cityService.findByFKId(Integer.parseInt(provinceId));
			
			PrintWriter pw = response.getWriter();
			pw.write("<?xml version='1.0' encoding='UTF-8'?>");
			pw.write("<root>");
			
			for(int i=0;i<allCities.size();i++){
				City city = allCities.get(i);
				pw.write("<city value='"+city.getId()+"'>"+city.getName()+"</city>");
			}
			
			pw.write("</root>");
			pw.flush();
			pw.close();
			
		}else if (method.equals("ajaxtwo")) {
			response.setContentType("text/xml;charset=utf-8");
			String cityId = request.getParameter("cityId");
			
			CountyService countyService = new CountyService();
			List<County> allCounties = countyService.findByFKId(Integer.parseInt(cityId));
			
			PrintWriter pw = response.getWriter();
			pw.write("<?xml version='1.0' encoding='UTF-8'?>");
			pw.write("<root>");
			
			for(int i=0;i<allCounties.size();i++){
				County county = allCounties.get(i);
				pw.write("<county value='"+county.getId()+"'>"+county.getName()+"</county>");
			}
			
			pw.write("</root>");
			pw.flush();
			pw.close();
			
		}else if (method.equals("fromSubmit")) {	//提交獲取資料
			
			String countId = request.getParameter("countyId");
			
			CountyService countyService = new CountyService();
			County county = countyService.findById(Integer.parseInt(countId));
			System.out.println("縣:"+county.getName());
			
			CityService cityService = new CityService();
			City city = cityService.findById(county.getCity_id());
			System.out.println("城市:"+city.getName());
			
			ProvinceServince provinceServince = new ProvinceServince();
			Province province = provinceServince.findById(city.getProvince_id());
			System.out.println("省:"+province.getName());
			
			System.out.println(province.getName()+"-"+city.getName()+"-"+county.getName());
			
		}else {
			ProvinceServince provinceServince = new ProvinceServince();
			List<Province> allProvinces = provinceServince.findAll();
			
			request.setAttribute("allProvinces", allProvinces);
			request.getRequestDispatcher("/Province_city_county.jsp").forward(request, response);
			
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

注:有什麼寫的不對的地方,請提出來,感謝