<%--
Created by IntelliJ IDEA.
User: 杨家兴
Date: 2022-5-3
Time: 9:44
To change this template use File | Settings | File Templates.
--%>
<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>省市级联查询</title>
<style>
#div1{margin: 0 auto;border:1px solid #000000; width: 300px;height: 100px}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function (){
$("#province").empty();
$.ajax({
url: "queryProvince",
type:"get",
dataType:"json",
success:function (json){
$.each(json,function (i,n){
$("#province").append("<option value='"+n.id+"'>"+n.name+" </option>");
})
}
})
$("#province").change(function (){
$("#city").empty();
var obj=$("#province>option:selected")
var id=obj.val();
$.post("queryCity",{id:id},function (json){
$.each(json,function (i,n){
$("#city").append("<option value='"+i+"'>"+n.name+" </option>");
})
})
})
})
</script>
</head>
<body>
<div id="div1">
<table>
<tr>
<td>省份名称</td>
<td>
<select id="province">
<option value="0" >请选择</option>
</select>
</td>
<td>
<button id="btn">加载省份</button>
</td>
</tr>
<tr>
<td>城市</td>
<td>
<select id="city">
<option value="0">请选择</option>
</select>
</td>
</tr>
</table>
</div>
</body>
</html>
String id=request.getParameter("id");
if (id!=null&&!"".equals(id.trim())){
System.out.println("进了servlet");
//调用dao获取所有的省份信息
String json="{}";
QueryCityDao queryCityDao=new QueryCityDao();
List<city> list= null;
try {
list = queryCityDao.queryCityById(Integer.valueOf(id));
} catch (SQLException e) {
e.printStackTrace();
}
//把list转为json格式的的数据
if(list!=null){
System.out.println(list);
ObjectMapper objectMapper=new ObjectMapper();
json=objectMapper.writeValueAsString(list);
//输出json数据,响应ajax请求,返回数据
response.setContentType("application/json;charset=utf-8");
PrintWriter pw=response.getWriter();
pw.println(json);
pw.flush();
pw.close();
}
}