效果图 (为显示加载数据动画,后台做了一秒钟延迟)
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>select2</title>
</head>
<script src="assets/js/jquery.min.js"></script>
<link href="resource/js/plugin/select2/select2.min.css" rel="stylesheet"/>
<script src="resource/js/plugin/select2/select2.min.js"></script>
<body>
<div style="width: 300px" >
<select id="select" data-placeholder="">
</select>
</div>
<script>
init();
function init() {
$("#select").select2({
width: '100%',
allowClear:true,
ajax: {
url: "../api/select/selectPage",
dataType: "json",
delay: 600,
data: function (params) {
return {
name: params.term, // search term
pageNum: params.page || 1
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
var page = params.page || 1;
return {
results: data["data"],
pagination: {
more: (page * 10) < data["totalNum"]
}
};
},
cache: true
},
escapeMarkup: function (markup) {
return markup;
}, // let our custom formatter work
minimumInputLength: 1, //至少输入多少个字符后才会去调用ajax
maximumInputLength: 20, //最多能输入多少个字符后才会去调用ajax
minimumResultsForSearch: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
}
function formatRepo (repo) {
if (repo.loading) return repo.text;
return '<div class="clearfix form-group">' +
'<div class="col-sm-12" style="padding-left: 1px">' + repo.name + '</div>' +
'</div>';
}
function formatRepoSelection (repo) {
return repo.name;
}
</script>
</body>
</html>
伪后台代码(您可以根据输入的属性name去分页查询数据库)
package com.wl.account.controller;
import com.wl.account.common.model.PageVo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by wl on 2021/4/22.
*/
@RestController
@RequestMapping("/api/select")
public class SelectController {
@RequestMapping("/selectPage")
public PageVo selectPage(Integer pageNum,String name) throws Exception{
//为了显示加载动画 这里延迟一秒钟
Thread.sleep(1000);
List<Map<String,String>> list = new ArrayList<>();
int max = pageNum * 10;
max = max >33 ? 33 : max;
for(int i = max - 9; i <= max ; i++){
Map<String,String> map = new HashMap<>();
map.put("id","id" + i);
map.put("name",name + i);
list.add(map);
}
PageVo pageVo = new PageVo();
pageVo.setData(list);
pageVo.setTotalNum(33);
pageVo.setPageSize(pageNum);
return pageVo;
}
}
注意后台返回值必须要有id属性。这个id属性也是select中下拉选项option 的value
查看选中的option 对应的value