基于XML,以POST方式,完成二级下拉联动【省份-城市】。效果当选择省份时,城市下拉框自动添加相对应的数据。
javascript代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <script type="text/javascript" src="js/createAjax.js"></script> <title>My JSP 'index.jsp' starting page</title> </head> <body> <select id="provinceID"> <option>请选择省份</option> <option>广东</option> <option>湖南</option> </select> <select id="cityID"> <option>请选择城市</option> </select> <script type="text/javascript"> //创建ajax对象 var ajax = createAjax(); //创建事件 document.getElementById("provinceID").onchange = function(){ //定位city下拉框节点 var citySelectElement = document.getElementById("cityID"); //再次选择省份时需先清空原来city下拉框之中的数据 var options = citySelectElement.options; var size = options.length; for(var i=1; i<size; i++){ citySelectElement.removeChild(options[1]); } //获取选中的节点的文本值 var province = this[this.selectedIndex].innerHTML; //准备发送请求 var method = "post"; var url = "${pageContext.request.contextPath}/provinceServlet?id="+new Date().getTime(); ajax.open(method,url); //真正发送请求 ajax.setRequestHeader("content-type","application/x-www-form-urlencoded"); var content = "province="+province; ajax.send(content); //监听服务器响应 ajax.onreadystatechange = function(){ //判断响应状态和响应码 if(ajax.readyState ==4){ if(ajax.status == 200){ //接收服务器响应回的字符串 var xmlDocument = ajax.responseXML; //获取服务器传递过来的xml文档中的city节点 var cityElements = xmlDocument.getElementsByTagName("city"); var size = cityElements.length; for(var i=0; i<size; i++){ //获取每个city节点之间的内容 var city = cityElements[i].firstChild.nodeValue; //创建option节点 var optionElement = document.createElement("option"); //设置option节点之间的内容 optionElement.innerHTML=city; //将option节点,条件到city下拉框之中 citySelectElement.appendChild(optionElement); } } } }; }; </script> </body> </html>
servlet代码:
package kerwin.ajax; 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 provinceServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { request.setCharacterEncoding("utf-8"); //注意:这时向浏览器发送的是xml文件,所以这里应该写text/xml;而不是text/html response.setContentType("text/xml;charset=UTF-8"); PrintWriter out = response.getWriter(); //接收参数 String province = request.getParameter("province"); out.write("<?xml version='1.0' encoding='UTF-8'?>"); out.write("<root>"); if("广东".equals(province)){ out.write("<city>广州</city>"); out.write("<city>中山</city>"); out.write("<city>深圳</city>"); }else if("湖南".equals(province)){ out.write("<city>长沙</city>"); out.write("<city>株洲</city>"); out.write("<city>湘潭</city>"); out.write("<city>张家界</city>"); } out.write("</root>"); } public void doPost(HttpServletRequest request,IOException { doGet(request,response); } }