搜索suggest

解决的问题:

  1. 因为select下拉选项太多需要做搜索建议
  2. 提高页面加载速度
  3. 实现一次之后 后续的接入只需修改js和枚举

主要思路:

  1. 使用动态sql 拼装需要的参数
  2. 使用枚举来动态的加载表
  3. 在页面中传入需要的枚举值 和 需要like的字段

引入插件magicsuggest

1
2
<script src="${pageContext.request.contextPath}/static/plugin/magicsuggest/magicsuggest-min.js"></script>
<link rel="stylesheet" href="${pageContext.request.contextPath}/static/plugin/magicsuggest/magicsuggest-min.css" />

在页面中加上相应的区域 可以为input或者div

1
<div id="mssupplier"></div>

在js中对上面的id进行绑定magicsuggest事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$(function() {
var mssupplier = $('#mssupplier').magicSuggest({
allowFreeEntries: false,
autoSelect: true,
placeholder:'请选择供应商',
data: '****.html', //数据请求地址
dataUrlParams: { //请求带的参数
category: 2, //对应的下面的枚举值
columns: ['name', 'supplierNo'] //请求的数据库字段(需要like的)
},
maxSelection: 1,
cls: 'col-xs-2',
infoMsgCls: 'hide'
});

$(mssupplier).on('selectionchange', function(e,m){
reloadGrid(); //改变之后需要所做的事情
});
}

设置枚举类对应请求参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* @author lemon
* @date 2017-12-20 18:24
* @desc 搜索建议插件枚举
*/
public enum SuggestCategoryEnum {
SHOP(1, "table1", true),
SUPPLIER(2, "table2", true),
USER(3, "table3", false),
PRODUCT(4, "table4", true);

private final int category; //分类
private final String tableName; //表名
private final boolean isMall; //其他参数(这个为作者的业务需求)

SuggestCategoryEnum(int category, String tableName, boolean isMall) {
this.category = category;
this.tableName = tableName;
this.isMall = isMall;
}

public int getCategory() {
return category;
}

public String getTableName() {
return tableName;
}

public boolean isMall() {
return isMall;
}

public static SuggestCategoryEnum getEnum(int category) {
for (SuggestCategoryEnum anEnum : values()) {
if (anEnum.getCategory() == category) {
return anEnum;
}
}
throw new RuntimeException("not find category:" + category);
}
}

请求后台sql mybatis

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<select id="listSuggest" resultType="cc.laowantong.entity.suggest.Suggest" parameterType="cc.laowantong.entity.suggest.SuggestParam">
select id,
concat
<foreach item="column" index="index" collection="matchColumns"
open="(" separator="," close=")">
${column}
</foreach> as name
from ${tableName}
<trim prefix="WHERE" prefixOverrides="AND|OR">
<foreach item="column" index="index" collection="matchColumns"
open="" separator="or" close="">
${column} like "%"#{keywords}"%"
</foreach>
</trim>
limit #{limit}
</select>

参考资料:http://nicolasbize.com/magicsuggest/doc.html

未经作者lemon允许 请勿转载,谢谢 :)

lemon wechat
欢迎大家关注我的订阅号 SeeMoonUp
写的不错?鼓励一下?不差钱?