Jquery 实现select 3级级联查询

 

 实现级联效果的思路:

1、 页面加载时,先显示第一级select,第二、三级的select隐藏,根据第一级select值的改变,再显示第二级select,依次类推;

2、只从后台获取第一级select的数据,第二级select的选项数据根据第一级select值的改变再动态更新,第三级select的选项数据再根据第二级select值的改变再做动态更新;

 

一、基于Jquery的jsp实现步骤:

1、页面引入Jquery插件:

 <script src="${pageContext.request.contextPath}/resources/js/jquery-3.0.0.min.js"></script>

 

2、页面加入三级的select标签:

 <!-- 一级select -->  
           <div >         
              <select   id="select-first"  name="categoryId"  data-getDataUrl="${pageContext.request.contextPath}/admin/spu/spu/getsonCategory">
                  <option value=''>请选择分类</option>
                  <c:forEach items="${rootCategorys}" var="rootCategory" varStatus="statu">
                    <option value="${rootCategory.id}" ${params.firstValue ==rootCategory.id  ? 'selected="selected"' :''}  >${rootCategory.categoryName}</option>
                  </c:forEach>                 
              </select>
           </div>
           <!-- 二级select -->
           <div  id="box-select-second" style="display:none;" >         
              <select   id="select-second" name="sonCategoryId"  data-getDataUrl="${pageContext.request.contextPath}/admin/spu/spu/getsonCategory" >                                         
             
              </select>
           </div>
            <!-- 三级select -->
           <div  id="box-select-third" style="display:none;" >         
              <select    id="select-third"  name="grandsoncategoryId"  data-getDataUrl="${pageContext.request.contextPath}/admin/spu/spu/getsonCategory" >  
                              
              </select>
           </div>                
           

3、使用jquery的change()方法,可以监听select的值一旦发生改变,就触发事件;

     使用$.ajax()异步方法请求后台数据,成功返回数据添加到下级select选项中:

              //级联select:一级select的值发生改变,触发二级的选项改变
              $("#select-first").change(function(){
                  //清空二级和三级select的旧选项
                  $("#select-second").empty();
                  $("#select-third").empty();
                  //请求二级select选项数据地址
                  var targetUrl = $(this).attr("data-getDataUrl");
                  //获得一级select的值
                  var firstValue = $(this).val();                  
                  //如果一级select的值为null,隐藏二、三级select,并返回
                  if(firstValue == ''){
                      $("#select-second").fadeOut("slow");
                      $("#select-third").fadeOut("slow");
                      return;
                  }            
                 
                 //根据一级select的值,异步获取数据更新二级的选项             
                  $.ajax({    
                      type:'get',        
                      url:targetUrl,    
                      data:{
                          parentId:firstValue
                      },    
                      cache:false,    
                      dataType:'json',    
                      success:function(secondDatas){                              
                          
                          //遍历回传的数据添加到二级select
                            $.each(secondDatas, function(key, secondData) {
                               
                                   var option = '<option value="'+secondData.id+'">'+secondData.categoryName+'</option>'      
                                   $("#select-second").append(option)
                                   
                            })                            
                            
                            //二级select展示
                           $("#box-select-second").fadeIn("slow");
                            //三级select隐藏
                              $("#box-select-third").fadeOut("slow");                                                 
                      },
                      error:function(){ 
                          alert("请求失败")
                        }
                   });                  
              });
              
              //级联select:二级select值改变,触发三级select变化
              $("#select-second").change(function(){
                  //清空三级slect的旧选项                
                  $("#select-third").empty();
                  //请求二级select选项数据地址
                  var targetUrl = $(this).attr("data-getDataUrl");
                  //二级select的值
                  var secondValue = $(this).val();
                  //如果一级select的值为null,隐藏三级select,并返回
                  if(secondValue == ''){                    
                      $("#select-third").fadeOut("slow");
                      return;
                  } 
                  //根据二级select的值,异步获取数据更新三级的选项    
                  $.ajax({    
                      type:'get',        
                      url:targetUrl,    
                      data:{
                          parentId:secondValue
                      },    
                      cache:false,    
                      dataType:'json',    
                      success:function(thirdDatas){                              
                          
                          //遍历回传的数据添加到三级select
                            $.each(thirdDatas, function(key, thirdData) {
                               
                                   var option = '<option value="'+thirdData.id+'">'+thirdData.categoryName+'</option>'      
                                   $("#select-third").append(option)
                                   
                            })
                            
                             //三级select显示出来
                              $("#box-select-third").fadeIn("slow");                                                 
                      },
                      error:function(){ 
                          alert("请求失败")
                        }
                   });                  
              });

 

4、后台是使用spring-mvc框架,前端ajax异步请求下级select数据在后台的相关实现是:

 

    /**
     * 获得子分类
     * @param parentId
     * @return
     */
    @RequestMapping(value="getsonCategory",method =RequestMethod.GET)
    @ResponseBody
    public List<TShopCategory> getsonCategory(Long parentId) {
        
        List<TShopCategory> sonCategorys =categoryService.getChildrenCategorys(parentId);
        
        return sonCategorys;        
    }

 

 ajax发送select的值和请求地址到后台,后台响应成功后回传子分类的集合给前端,

 

 前端以json格式获得,前端使用Jquery的$.each遍历分类集合,生成<option>标签,使用append()方法将新生成的<option>标签添加到下级的select当中。

 

 

下图为实现效果图:

 

这是只基于Jquery的 三级select级联查询,没有任何美化和增强功能,下面介绍基于bootstrap框架+bootstrap-select组件的三级select级联查询功能,

美化select选择框和增加选项搜索。

 

二、基于Jquery、bootstrap框架、bootstrap-select组件,实现三级查询步骤:

 1、在jsp引入相关文件(bootstrap-select组件依赖于bootstrap框架,bootstrap框架依赖于Jquery):

<!-- 引入 Bootstrap 样式-->
      <link href="${pageContext.request.contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">        
      <!-- select样式 -->
      <link href="${pageContext.request.contextPath}/resources/css/select/bootstrap-select.min.css" rel="stylesheet">
        
           
      <!-- jQuery (Bootstrap 需要引入 jQuery) -->
      <script src="${pageContext.request.contextPath}/resources/js/jquery-3.0.0.min.js"></script>
      <!-- bootstrap插件 -->
      <script src="${pageContext.request.contextPath}/resources/js/bootstrap.min.js"></script>         
      <!-- bootstrap-select组件 -->
      <script src="${pageContext.request.contextPath}/resources/js/select/bootstrap-select.min.js"></script>
      <script src="${pageContext.request.contextPath}/resources/js/select/defaults-zh_CN.min.js"></script>

2、jsp加入3级的select:

 <!--搜索栏-->
       <form id="listForm" class="row" action=""  method = "GET">                          
         <div class="col-md-12 ">      
           <div class="form-group col-md-2 " id="spu-select-firstCategory">
              <!-- 一级select -->         
              <select  class="form-control selectpicker show-tick reset" id="select-first" title="请选择分类" name="firstValue"  data-getDataUrl="${pageContext.request.contextPath}/admin/spu/spu/getsonCategory" data-live-search="true"  data-size="6">
                  <c:forEach items="${rootCategorys}" var="rootCategory" varStatus="statu">
                    <option value="${rootCategory.id}" ${params.firstValue ==rootCategory.id  ? 'selected="selected"' :''}  >${rootCategory.categoryName}</option>
                  </c:forEach>                 
              </select>
           </div>
           <!-- 二级select -->    
           <div class="form-group col-md-2  " id="box-select-second" style="display:none;" >         
              <select   class="form-control selectpicker show-tick reset" id="select-second" title="二级分类" name="sonCategoryId"  data-getDataUrl="${pageContext.request.contextPath}/admin/spu/spu/getsonCategory" data-live-search="true"  data-size="6">
                                         
              </select>
           </div>
           <!-- 三级select -->    
           <div class="form-group col-md-2 " id="box-select-third" style="display:none;" >         
              <select   class="form-control selectpicker show-tick reset" id="select-third" title="三级分类" name="categoryId"  data-getDataUrl="${pageContext.request.contextPath}/admin/spu/spu/getsonCategory" data-live-search="true"  data-size="6">  
                              
              </select>
           </div>
           <div class="form-group form-inline col-md-2 ">     
              <input id="formSearch" type="button" class="form-control" value="搜索" >        
           </div>                          
          </div>                       
       </form>

3、Jquery实现级联效果,注意:因为引入了bootstrap-select组件,异步ajax获得回传的数据添加到select时,需要调用selectpicker('refresh')方法刷新才看得见新的option选项:

<script type="text/javascript">
          $().ready(function(){
                     
              //级联select:首级select的值发生改变,触发二级的选项改变
              $("#select-first").change(function(){
                  //清空二级和三级select的旧选项
                  $("#select-second").empty();
                  $("#select-third").empty();
                  //请求二级select选项数据地址
                  var targetUrl = $(this).attr("data-getDataUrl");
   
                  //一级select的值
                  var firstValue = $(this).val();  
                  
                  //如果一级select的值为null,隐藏二、三级select,并返回
                  if(firstValue == ''){
                      $("#select-second").fadeOut("slow");
                      $("#select-third").fadeOut("slow");
                      return;
                  }            
                 
                 //根据一级的值改变,异步获取数据更新二级的选项             
                  $.ajax({    
                      type:'get',        
                      url:targetUrl,    
                      data:{
                          parentId:firstValue
                      },    
                      cache:false,    
                      dataType:'json',    
                      success:function(secondDatas){                              
                          
                          //遍历回传的数据添加到二级select
                            $.each(secondDatas, function(key, secondData) {
                               
                                   var option = '<option value="'+secondData.id+'">'+secondData.categoryName+'</option>'      
                                   $("#select-second").append(option)
                                   
                            })
                             //bootstap-select控件:需刷新对应select                           
                              $("#select-second").selectpicker('refresh');
                            
                            //二级select展示
                           $("#box-select-second").fadeIn("slow");
                            //三级select隐藏
                              $("#box-select-third").fadeOut("slow");                                                 
                      },
                      error:function(){ 
                          bootbox.alert("请求失败")
                        }
                   });                  
              });
              
              //级联select:二级select值改变,触发三级select变化
              $("#select-second").change(function(){
                  //清空三级slect的旧选项                
                  $("#select-third").empty();
                  //请求二级select选项数据地址
                  var targetUrl = $(this).attr("data-getDataUrl");
                  //二级select的值
                  var secondValue = $(this).val();
                  //如果一级select的值为null,隐藏三级select,并返回
                  if(secondValue == ''){                    
                      $("#select-third").fadeOut("slow");
                      return;
                  } 
                  //根据二级的值改变,异步获取数据更新三级的选项    
                  $.ajax({    
                      type:'get',        
                      url:targetUrl,    
                      data:{
                          parentId:secondValue
                      },    
                      cache:false,    
                      dataType:'json',    
                      success:function(thirdDatas){                              
                          
                          //遍历回传的数据添加到三级select
                            $.each(thirdDatas, function(key, thirdData) {
                               
                                   var option = '<option value="'+thirdData.id+'">'+thirdData.categoryName+'</option>'      
                                   $("#select-third").append(option)
                                   
                            })
                            //bootstap-select控件:需刷新对应select                           
                              $("#select-third").selectpicker('refresh');
                            
                             //三级select显示出来
                              $("#box-select-third").fadeIn("slow");                                                 
                      },
                      error:function(){ 
                          alert("请求失败")
                        }
                   });                  
              });            
                 
          });
                                 
</script>

 

4、后台是使用spring-mvc框架,前端ajax异步请求下级select数据在后台的相关实现是:

    /**
     * 获得子分类
     * @param parentId
     * @return
     */
    @RequestMapping(value="getsonCategory",method =RequestMethod.GET)
    @ResponseBody
    public List<TShopCategory> getsonCategory(Long parentId) {
        
        List<TShopCategory> sonCategorys =categoryService.getChildrenCategorys(parentId);
        
        return sonCategorys;        
    }

 ajax发送select的值和请求地址到后台,后台响应成功后回传子分类的集合给前端,

 前端以json格式获得,前端使用Jquery的$.each遍历分类集合,生成<option>标签,使用append()方法将新生成的<option>标签添加到下级的select当中。

 

 

图为整合了bootstrap框架+bootstrap-select组件实现的三级select效果:

 

 

 

 

 

转载于:https://www.cnblogs.com/kenhome/p/7728181.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您解答这个问题。 首先,我们需要在前端页面中定义三个下拉菜单,分别表示三菜单。然后,我们需要使用 AJAX 技术实现级联效果,即当用户选择第一菜单时,自动加载第二菜单的选项,当用户选择第二菜单时,自动加载第三菜单的选项。 以下是一个基本的 AJAX 实现级联下拉菜单的示例代码: HTML 代码: ```html <select id="first-level"> <option value="">请选择</option> <option value="1">一菜单1</option> <option value="2">一菜单2</option> <option value="3">一菜单3</option> </select> <select id="second-level"> <option value="">请选择</option> </select> <select id="third-level"> <option value="">请选择</option> </select> ``` JavaScript 代码: ```javascript $(function () { // 当第一菜单选项改变时,加载第二菜单选项 $('#first-level').change(function () { $.ajax({ url: '/getSecondLevelOptions', // 后端接口地址,需要自己实现 type: 'POST', data: {firstLevelValue: $(this).val()}, // 发送的数据,根据实际情况调整 dataType: 'json', success: function (data) { // 清空第二菜单选项 $('#second-level').empty(); // 添加第二菜单选项 $.each(data, function (index, item) { $('#second-level').append('<option value="' + item.value + '">' + item.label + '</option>'); }); // 触发第二菜单选项的 change 事件,以加载第三菜单选项 $('#second-level').change(); } }); }); // 当第二菜单选项改变时,加载第三菜单选项 $('#second-level').change(function () { $.ajax({ url: '/getThirdLevelOptions', // 后端接口地址,需要自己实现 type: 'POST', data: {secondLevelValue: $(this).val()}, // 发送的数据,根据实际情况调整 dataType: 'json', success: function (data) { // 清空第三菜单选项 $('#third-level').empty(); // 添加第三菜单选项 $.each(data, function (index, item) { $('#third-level').append('<option value="' + item.value + '">' + item.label + '</option>'); }); } }); }); }); ``` 在上面的代码中,我们使用 jQuery 库来实现 AJAX 请求和 DOM 操作。当第一菜单选项改变时,我们向后端发送一个 POST 请求,请求参数为当前选中的一菜单的值,后端需要根据这个值返回对应的二菜单选项。当收到后端返回的数据后,我们清空第二菜单选项并添加新的选项,然后触发第二菜单选项的 change 事件,以加载第三菜单选项。当第二菜单选项改变时,我们向后端发送一个 POST 请求,请求参数为当前选中的二菜单的值,后端需要根据这个值返回对应的三菜单选项。当收到后端返回的数据后,我们清空第三菜单选项并添加新的选项。 需要注意的是,上面的代码中的接口地址和请求参数需要根据实际情况进行调整,另外,后端接口需要根据前端发送的请求参数返回对应的选项数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值