1、 首先需要在jsp页面导入有关select2的js和css文件,前提也需要Jquery的js文件
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<script type="text/javascript" src="<%=basePath%>common/jquery/jquery.1.9.1.js"></script>
或者到官网下载:http://select2.github.io/
或者这里:https://download.youkuaiyun.com/download/su1573/10657038
2、 然后在js文件中,编写相关的js
function EmploreName_select2(){
var EmploreId ;
if(comcodeC==03){
EmploreId = usercodeC;
}else{
EmploreId = $('#CustomName').combobox('getValue');
}
$("#EmploreName").select2({
ajax: {
url : basePath+'public.asp',
dataType : 'json',
type : 'post',
data : function (params) {
return {
funcId : "EmploreNameQ",
EmploreId: EmploreId,
perName : params.term //接收搜索框输入的姓名
};
},
processResults: function (data) { //data返回数据
var options = new Array();
$(data.items).each(function(i, o) {
options.push({ //获取select2个必要的字段,id与text
id : o.Code, //取出items中Code赋值给id
text : o.CodeName //取出items中CodeName赋值给text
});
});
return {
results: options //返回数据
};
},
cache: true
},
placeholder: "输入姓名搜索...",
allowClear: true, //选中之后,可手动点击删除
escapeMarkup: function (markup) { return markup; }, // 字符转义处理自定义格式化防止xss注入
formatResult: function formatRepo(repo){return repo.text;}, // 函数用来渲染结果
formatSelection: function formatRepoSelection(repo){return repo.text;} // 函数用于呈现当前的选择
});
}
说明:
- perName : params.term 为搜索框中的内容,下图红框内容所示
- data.items 为后台返回数据中的json集合 (不一定是items根据项目中定义的所示)
- placeholder占位提示文字,如果需要清除功能,则必须设置placeholder
- allowClear: true 设置为true,则表示可以手动清除,点击选择框后面“×”
- minimumInputLength 最小需要输入多少个字符才进行查询,与之相关的maximumSelectionLength表示最大输入限制。(根据需要选择添加,不设置,则自动查询)
- escapeMarkup字符转义处理
- templateResult返回结果回调function formatRepo(repo){return repo.text},这样就可以将返回结果的的text显示到下拉框里,当然你可以return repo.text+”1”;等
templateSelection选中项回调function formatRepoSelection(repo){return repo.text}
3、 在后台处理前台传入的参数
其中EmploreId和perName 需要在sql中用到
select AC01.AAC003 codeName ,AC01.AAC001 Code from AC01,AC19
where 1=1
and ac01.aac001=AC19.AAC001
<if test="pd.EmploreId!=null and pd.EmploreId!=''and pd.EmploreId!='00'">
and AC19.aab001=#{pd.EmploreId,jdbcType=VARCHAR}
</if>
<if test="pd.perName!=null and pd.perName!=''">
and ac01.aac003 like concat(concat('%',#{pd.perName,jdbcType=VARCHAR}),'%')
</if>
4、 效果展示

author:su1573