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>jquery+json两级联动下拉菜单的实现</title>
<script type="text/javascript" src="staty/js/jquery-1.5.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#sheng").change(function(){
var provinceid = $(this).val();
$.ajax({
type: "GET",
url: "servlet/demo9",
data:{provinceid:provinceid},
dataType:"json",
success: function(msg){
alert(msg);
$("#city").empty();
$.each(msg,function(i,obj){
$("#city").append("<option value='"+obj.value+"'>"+obj.name+"</option>");
});
//for(Objct obj:list){
//}
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert(textStatus);
alert(errorThrown);
}
});
});
});
</script>
</head>
<body>
<div>
省<select id="sheng">
<option value="1">安徽</option>
<option value="2">江苏</option>
<option value="3">河北</option>
</select>
市:<select id="city">
</select>
</div>
</body>
</html>
demo9代码如下:
package com.ambow;
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 demo9 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String provinceid = request.getParameter("provinceid");
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
if(provinceid.equals("1")){
out.println("[{/"name/":/"六安/",/"value/":20053}," +
"{/"name/":/"安庆/",/"value/":20065}," +
"{/"name/":/"合肥/",/"value/":20025}]");
}
if(provinceid.equals("2")){
out.println("[{/"name/":/"苏州/",/"value/":20053}," +
"{/"name/":/"南京/",/"value/":20065}," +
"{/"name/":/"常州/",/"value/":20025}]");
}
if(provinceid.equals("3")){
out.println("[{/"name/":/"保定/",/"value/":20053}," +
"{/"name/":/"石家庄/",/"value/":20065}," +
"{/"name/":/"唐山/",/"value/":20025}]");
}
out.flush();
out.close();
}
}