利用jquery.chained.remote实现多级级联

时间:2022-05-22 02:18:19

多级级联一直是前端比较烦人的一个功能,本次用jquery的插件,chained.remote实现多级级联。

应用场景:至少有二个下拉框,下拉框的个数不定。

应用步骤:

1.引入js文件,当然这个插件需要自己去下载。

<!-- 多级联动 -->
<script type="text/javascript" src="./static/js/jquery.chained.remote.min.js"></script>

2.两个下拉框

<!--第一个下拉框-->
<div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"
style="padding-bottom: 2px">
<div class="input-group input-group-sm">
<span class="input-group-addon">材料/产品</span> <select
class="form-control" name="categoryType" id="categoryType"
onchange="setParm(this.name, this.value)">
<option value="">所有</option>
<option value="0"><c:if test='${pm.categoryType==1}'>selected</c:if>材料
</option>
<option value="1"><c:if test='${pm.categoryType==2}'>selected</c:if>产品
</option>
</select>
</div>
</div>
<!--第二个下拉框-->
<div class="col-lg-2 col-md-3 col-sm-4 col-xs-6"
style="padding-bottom: 2px">
<div class="input-group input-group-sm">
<span class="input-group-addon">父级类别</span> <SELECT
class="form-control" name="parentCategoryId" id="parentCategoryId"
onchange="setParm(this.name, this.value)">
<OPTION value="">请选择</OPTION>
</SELECT>
</div>
</div>

我想实现的是选择第一个下拉框的材料或者产品的时候,会导致第二个下拉框显示不同的内容。注意第一个下拉框的id是categoryType,第二个下拉框的id是parentCategoryId.

3.写入如下js代码

$(function() {
//二级联动
$("#parentCategoryId").remoteChained("#categoryType", "parentCategoryListByCategoryType"); });
parentCategoryId和categoryType分别对应第二个和第一个下拉框的id,parentCategoryListByCategoryType是ajax获取数据的url。
4.接下来就是编写parentCategoryListByCategoryType的代码。
@ResponseBody
@RequestMapping("parentCategoryListByCategoryType")
public String parentCategoryListByCategoryType(int categoryType) {
JSONObject jsonObject = categoryService
.getRootCategoryListByCategoryType(categoryType);
return jsonObject.toString();
}

public JSONObject getRootCategoryListByCategoryType(int categoryType){
try {
List<TCategory>rootCategoryList=baseDao.findTListByParam("TCategoryMapper.selectRootCategoryByCategoryType", categoryType);
JSONObject jsonObject=new JSONObject();
for(TCategory category:rootCategoryList){
jsonObject.put(category.getCategoryId().toString(), category.getCategoryName());
}
return jsonObject;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; }
    <select id="selectRootCategoryByCategoryType" resultMap="BaseResultMap"
parameterType="java.lang.Integer">
select
<include refid="Base_Column_List" />
from t_category
where is_del=0 and is_root=1
<if test="categoryId!=0">
and
category_type=#{categoryId,jdbcType=INTEGER}
</if>
order by sort_num
</select>

可以看到我们取得的数据是json格式的。这样便完成了二级级联的效果,多级级联只要在这个基础上按同样的方法做就可以了。

PS:应用的框架是ssm.