多个下拉框在一起,后面的下拉框会根据前面选择的内容的变化而变化。
showCity.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'showCity.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
var xmlhttp;
function GetXmlHttpObject()
{
xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function sendRequest(){
GetXmlHttpObject();
if(xmlHttp){
var url = "servlet/ShowCities";
var data="province="+$('sheng').value;
xmlHttp.open("post", url, true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//指定回调函数
xmlHttp.onreadystatechange=deal;
//发送get请求,如果是get请求填入null
//如果是post请求,则填入实际的数据。
xmlHttp.send(data);
}
}
function deal(){
//==4表示完成,200表示取出数据
if(xmlHttp.readyState==4&&xmlHttp.status==200){
var citys=xmlHttp.responseText;
citys=eval("("+citys+")");
$('city').length=0;
var myOption1=document.createElement("option");
myOption1.value="";
myOption1.innerText="--城市--";
$('city').appendChild(myOption1);
for(var i=0;i<citys.length;++i){
var city=citys[i].cityname;
var myOption=document.createElement("option");
myOption.value=city;
myOption.innerText=city;
$('city').appendChild(myOption);
}
}
}
function $(id){
return document.getElementById(id);
}
</script>
</head>
<body>
<select id="sheng" οnchange="sendRequest();">
<option value="">---省---</option>
<option value="zhejiang">浙江</option>
<option value="jiangsu" >江苏</option>
</select>
<select id="city">
<option value="">--城市--</option>
</select>
</body>
</html>
showCities.java
public class ShowCities extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.addHeader("Content-Type", "text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String province=request.getParameter("province");
String res="";
if(province.equals("zhejiang")){
res="[{'cityname':'杭州'},{'cityname':'温州'},{'cityname':'宁波'}]";
}else if(province.equals("jiangsu")){
res="[{'cityname':'南京'},{'cityname':'徐州'},{'cityname':'苏州'}]";
}
out.println(res);
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}