<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script th:src="@{/js/jquery-3.5.1.js}"></script>
<script>
$(function () {
$('#s1').blur(function () {
//获取所选的id
var id = $('#s1').val();
$.ajax({
type: "GET",
url:"/city",
data: {id},
dataType: "json",
success: function (result) {
$('#s2').empty();
$.each(result,function () {
$('#s2').append("<option value='"+this.id+"'>"+this.name+"</option>")
})
}
})
})
})
</script>
<body>
<select id="s1">
<option th:each="n:${allName}" th:text="${n.name}" th:value="${n.id}"></option>
</select>
<select id="s2">
</select>
</body>
</html>
@Controller
@RequestMapping("")
public class IndexController {
@Autowired
private ProvinceService provinceService;
@Autowired
private CityService cityService;
@RequestMapping("/index")
public String findAllName(Model model) {
List<Province> allName = provinceService.findAllName();
model.addAttribute("allName",allName);
return "/index/index";
}
//根据传入的省份id查找该省份所有的城市
@RequestMapping("/city")
@ResponseBody
public List<City> selectAllCity(Integer id) {
System.out.println(id);
List<City> city = cityService.selectAllCity(id);
System.out.println(city);
return city;
}
}