实现前端两个下拉框的联动(前端基于bootstrapt和freemarker,后台基于springboot+jpa)

本文介绍了一个基于Java Spring Boot的前后端联动示例,通过控制器、服务层和数据库查询来实现二级网格数据的动态加载。前端使用jQuery AJAX在选择一级网格后动态更新二级网格选项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这种联动的话整体思路是:第一级没有任何约束,直接从数据库查询即可;第二级数据查询条件是第一级实体类字段

controller 层:

@ApiOperation(value = "二级网格与一级网格联动", notes = "二级网格与一级网格联动")
@SysLog("二级网格与一级网格联动")
@PostMapping(value = "/findSecondByGrid")
public List<MapSecondGrid> findSecondByGrid(String oneLevelGrid) {
    return this.mapGridService.findSecondByGrid(oneLevelGrid);
}

service 层:

/**
 * @return  二三级网格联动
 */
List<MapSecondGrid> findSecondByGrid(String oneLevelGrid);

serviceImpl 层:

/**
 * @return  二级网格json数据
 */
@Override
public List<MapSecondGrid> findSecondByGrid(String oneLevelGrid) {
    return this.mapSecondGridRepository.findSecondByGrid(oneLevelGrid);
}

Repository 层:

/**
 * @return 二级网格json数据
 */
@Query(value = "select * from map_second_grid where one_level_grid = ?1", nativeQuery = true)
List<MapSecondGrid> findSecondByGrid(String oneLevelGrid);

----------------------------------前端代码-------------------------------

<script>
    $(document).ready(function(){
        $.ajax({
            type: "POST",
            dataType: "json",
            cache: false,
            url: getRootPath() + "/map/grid/one",      //这是一级下拉框从数据库取得数据的接口
            success: function (result) {
                $("#firstGridId").empty();
                $("#firstGridId").append("<option value=''>请选择</option>");
                for (var i=0;i<result.length;i++)
                {
                    $("#firstGridId").append("<option value="+result[i].name+">"+result[i].name+"</option>");
                }
            },
            error: function (result) {
                layer.alert("保存失败1,"+result.mess);
            }
        });
    });

    function onchangeMed(value){
        $.ajax({
            type: "POST",
            dataType: "json",
            cache: false,
            data: {oneLevelGrid:value},
            url: getRootPath() + "/map/grid/findSecondByGrid",  //这是二级下拉框根据一级字段的值从数据库取得数据的接口
            success: function (result) {
                console.log(result);
                $("#twoLevelGrid").empty();
                $("#twoLevelGrid").append("<option value=''>请选择</option>");
                for (var i=0;i<result.length;i++)
                {
                    $("#twoLevelGrid").append("<option value="+result[i].gridName+">"+result[i].gridName+"</option>");
                }
            },
            error: function (result) {
                layer.alert("保存失败2,"+result.mess);
            }
        });
    }


</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值