springboot整合Mybatis(利用了Mybatis的反向工程自动生成pojo,mapper接口和xml文件)+Ajax+jQuery实现下拉列表联动

在这里插入图片描述
在这里插入图片描述

<!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;
    }
}
posted @ 2022-11-11 20:47  小匠i  阅读(41)  评论(0)    收藏  举报