级联查询
数据表信息
Controller层
@Controller
public class MainController {
@Autowired
private ProvinceMapper provinceMapper;
@Autowired
private CityMapper cityMapper;
@RequestMapping("/index")
public String index(){
return "index";
}
@RequestMapping(value = "/search",produces = "application/json;charset=utf-8")
@ResponseBody
public Object queryProvince(HttpServletResponse response,HttpServletRequest request) throws JsonProcessingException, UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
List<Province> provinceList = provinceMapper.queryAllProvince();
ObjectMapper mapper = new ObjectMapper();
String string = mapper.writeValueAsString(provinceList);
return string;
}
@RequestMapping(value = "/search_city",produces = "application/json;charset=utf-8")
@ResponseBody
public Object queryCityById(Integer id) throws JsonProcessingException {
List<City> cityList = cityMapper.queryCityById(id);
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(cityList);
return str;
}
}
JSP页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
// 设置动态初始访问路径(这里本地是http://127.0.0.1:8080/crm/)
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<title>级联查询</title>
<script src="./jQuery/jquery-3.6.0.js"></script>
<script type="text/javascript">
//封装方法:不用点击按钮就可以遍历并选择省份
// (这样不用点击就能遍历并选择省份,当然这里点击按钮也可以,因为调用了这个方法)
function getProvince() {
$.ajax({
url:"search",
dataType:"json",
type:"get",
success:function (data) {
//每次点击“查询”要清空原来的下拉框数据,不然由于append方法会一直往后拼接
$("#province").empty()
//把默认的“请选择..”进行重新添加
$("#province").append("<option value='0'>请选择...</option>")
$.each(data,function (index,element) {
$("#province").append("<option value='"+element.id+"'>"+element.name+"</option>")
})
}
})
}
$(function () {
getProvince()
//添加省份下拉框
$("#search").click(function () {
getProvince()
})
//思考:如果省份下拉框内容发生改变,则触发City相关事件
$("#province").change(function () {
//根据省份的id来遍历查询对应的城市信息,并展示在下拉框
var id = $("#province > option:selected").val()
if (id>0){
//发起ajax请求获取对应省份的城市列表
$.get("search_city",{"id":id},function (resp) {
$("#city").html("")
$("#city").append("<option value='0'>请选择...</option>")
$.each(resp,function (index,element){
$("#city").append("<option value='"+element.id+"'>"+element.name+"</option>")
})
})
}else {
alert("请选择省份!")
}
})
})
</script>
</head>
<body>
<div align="center">
<p>级联查询</p>
<table>
<tr>
<td>省份列表:</td>
<td>
<select id="province">
<option value="0">请选择...</option>
</select>
<button id="search">查询</button>
</td>
</tr>
<tr>
<td>城市列表:</td>
<td>
<select id="city">
<option value="0">请选择...</option>
</select>
</td>
</tr>
</table>
</div>
</body>
</html>