页面效果:
1.前端页面的html以及js代码
<select name="dealerStatus" id="dealerStatusSelect" lay-verify="required" ></select>
// 下拉选初始化
function initSelect() {
ajax(ctx+"/select/sys/rating_type1",{},function (data) {
var optionsHtml = '<option value="">请选择</option></select>';
data.forEach(function(option){
optionsHtml += '<option value="' + option.value + '">' + option.text + '</option>';
});
console.log(optionsHtml)
document.getElementById("dealerStatusSelect").innerHTML = optionsHtml;
// 重新渲染 select 组件
layui.use('form',function () {
var form = layui.form;
form.render()
})
})
}
2.后端数据的封装
controller层:
@RequestMapping(value = "/sys/{type}")
public List<DictVo> dict(@PathVariable("type")String type,@RequestParam(value="sort",required=false)String sort,HttpServletRequest request) throws Exception {
if(StringUtils.isEmpty(sort)){
return DictUtil.getDictVoList(type);
}
return DictUtil.getDictVoListBySort(type);
}
DictUtil中的方法
public static List<DictVo> getDictVoList(String type) throws IOException {
List<DictVo> dictList = new ArrayList<DictVo>();
List<Dictionary> list=getDictList(type);
if(list!=null){
for (Dictionary dictionary : list) {
DictVo dv = new DictVo();
dv.setValue(dictionary.getDictCode());
dv.setText(dictionary.getDictCode() + "-" + dictionary.getDictNameCn());
dv.setSort(dictionary.getSort());
dictList.add(dv);
}
}
// 排序
Util.getDictVoValueList(dictList);
return dictList;
}
public static List<DictVo> getDictVoListBySort(String type) throws IOException {
List<DictVo> dictList = new ArrayList<DictVo>();
List<Dictionary> list=getDictList(type);
if(list!=null){
for (Dictionary dictionary : list) {
DictVo dv = new DictVo();
dv.setValue(dictionary.getDictCode());
dv.setText(dictionary.getDictCode() + "-" + dictionary.getDictNameCn());
dv.setSort(dictionary.getSort());
dictList.add(dv);
}
}
// 排序
Util.getDictVoSortList(dictList);
return dictList;
}
// 获取到字段集合
public static List<Dictionary> getDictList(String type) throws IOException {
String json=RedisUtil.getHash(RedisKeyUtil.USER_DICTS, type);
if(StringUtils.isNotEmpty(json)){
return JsonUtils.parseArray(json, Dictionary.class);
}
return null;
}
这个方法主要就是是代码变得跟灵活一些 不需要在前端写死下拉选 只需要配置一下字典 通过字典类型访问后端,获取到相关下拉选得字典集合