select2 is a jQuery plug-in, which is an upgraded version of the ordinary form select component. This article mainly introduces you to the jQuery plug-in select2, which uses ajax to efficiently query big data lists (searchable and paging). Friends who need it can refer to it. I hope it can help you.
You can customize searches, remote data sets (Remote data, the main introduction point of this article), infinite scrolling (data paging function, which is great), and many high-end parameter settings (next time if needed) introduce).
There are 40 built-in international languages, but here we only need to use Chinese.
Supports built-in support for both modern and traditional browsers, even the annoying IE8.
So, now let us start a fantasy journey of select2!
1. Stunning effects, come and have a look
<link> <script></script>
<link> <script></script> <script></script>
<select> <option>沉默王二</option> </select>
Provide a default option, which is displayed before the page is retrieved.
<script> $(function() { $("select.js-data-example-ajax").each( function() { var $this = $(this); $this.select2({ language : "zh-CN",// 指定语言为中文,国际化才起效 inputMessage : $this.attr("inputMessage"),// 添加默认参数 ajax : { url : $this.attr("href"), dataType : 'json', delay : 250,// 延迟显示 data : function(params) { return { username : params.term, // 搜索框内输入的内容,传递到Java后端的parameter为username page : params.page,// 第几页,分页哦 rows : 10// 每页显示多少行 }; }, // 分页 processResults : function(data, params) { params.page = params.page || 1; return { results : data.data,// 后台返回的数据集 pagination : { more : params.page < data.total// 总页数为10,那么1-9页的时候都可以jQuery plug-in select2 uses ajax to efficiently query large data lists } }; }, cache : false }, escapeMarkup : function(markup) { return markup; }, // let our custom formatter work minimumInputLength : 1,// 最少输入一个字符才开始检索 templateResult : function(repo) {// 显示的结果集格式,这里需要自己写css样式,可参照demo // 正在检索 if (repo.loading) return repo.text; var markup = repo.username; markup += repo.realname; var markup = "<p class='select2-result-repository clearfix'>" + "<p class='select2-result-repository__avatar'><img src='" + repo.headimgUrl + "' />" + "<p class='select2-result-repository__meta'>" + "<p class='select2-result-repository__title'>" + repo.username + ""; if (repo.realname) { markup += "<p class='select2-result-repository__description'>" + repo.realname + ""; } markup += "<p class='select2-result-repository__statistics'>" + "<p class='select2-result-repository__forks'><i class='fa fa-user'> 下级会员数" + repo.children_count + " " + "" + ""; return markup; }, templateSelection : function(repo) { return repo.realname || repo.text; }// 列表中选择某一项后显示到文本框的内容 }); }); }); </script>
@RequestMapping(value = "loadMembersInfo") public void loadMembersInfo(HttpServletRequest request, HttpServletResponse response) throws IOException { Integer uid = StrUtil.parseStringToInt(request.getParameter("uid")); Members mem = this.memberService.selectByPrimaryKey(uid); // 分页参数的转换,需要和前台select2进行匹配,下文放代码 BaseConditionVO vo = getBaseConditionVOForTable(request); vo.addParams("username", StrUtil.getUTF8String(request.getParameter("username"))); vo.addParams("uid", uid); // 封装结果集,和前台select2也是匹配的。 PageGrid page = createPageGrid(this.membersMapper.getPromoterList(vo, vo.createRowBounds()), vo, this.membersMapper.searchPromoterTotalCount(vo)); // 以json格式写入到response out(page, response); }
BaseConditionVO.Java public class BaseConditionVO { public final static int PAGE_SHOW_COUNT = 50; private int pageNum = 1; private int numPerPage = 0; private int totalCount = 0; private String orderField; private String orderDirection; /** * @Fields ps : 对参数类型进行封装. */ private Map<string> mo = new HashMap<string>(); public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getNumPerPage() { return numPerPage > 0 ? numPerPage : PAGE_SHOW_COUNT; } public void setNumPerPage(int numPerPage) { this.numPerPage = numPerPage; } public String getOrderField() { return orderField; } public void setOrderField(String orderField) { this.orderField = orderField; } public String getOrderDirection() { return "desc".equals(orderDirection) ? "desc" : "asc"; } public void setOrderDirection(String orderDirection) { this.orderDirection = orderDirection; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getStartIndex() { int pageNum = this.getPageNum() > 0 ? this.getPageNum() - 1 : 0; return pageNum * this.getNumPerPage(); } public RowBounds createRowBounds() { RowBounds ro = new RowBounds(this.getStartIndex(), this.getNumPerPage()); return ro; } /** * @Title: addParams * @Description: 添加查询条件 * @param key * @param value */ public void addParams(String key, Object value) { this.getMo().put(key, value); } /** * @Title: getParams * @Description: 获取查询条件 * @param key * @return */ public Object getParams(String key) { return this.getMo().get(key); } /** * @return the mo */ public Map<string> getMo() { return mo; } /** * @param mo * the mo to set */ public void setMo(Map<string> mo) { this.mo = mo; } }</string></string></string></string>
protected BaseConditionVO getBaseConditionVOForTable(HttpServletRequest req) { BaseConditionVO vo = new BaseConditionVO(); // 当前页 int currentPage = StrUtil.parseStringToInt(req.getParameter("page")); // 一页显示多少行 int sizes = StrUtil.parseStringToInt(req.getParameter("rows")); // 排序 String sortOrder = StrUtil.getString(req.getParameter("sord")); String sortCol = StrUtil.getString(req.getParameter("sidx")); vo.setNumPerPage(sizes); vo.setPageNum(currentPage); vo.setOrderField(sortCol); vo.setOrderDirection(sortOrder); return vo; }
@XStreamAlias("pageGrid") @SuppressWarnings("rawtypes") public class PageGrid { private int page; // 总页数,和select2的processResults.pagination匹配 private int total; private int records; // 数据结果集,和select2的processResults.results匹配 private List data; public int getPage() { return this.page; } public void setPage(int page) { this.page = page; } public int getTotal() { return this.total; } public void setTotal(int total) { this.total = total; } public int getRecords() { return this.records; } public void setRecords(int records) { this.records = records; } public List getData() { return this.data; } public void setData(List data) { this.data = data; } }
protected PageGrid createPageGrid(List list, BaseConditionVO vo, int searchTotalCount) { PageGrid pageGrid = new PageGrid(); // 数据 pageGrid.setData(list); // 当前页 pageGrid.setPage(vo.getPageNum()); // 总数目 pageGrid.setRecords(list.size()); // 总页数 int total = 0; if (pageGrid.getRecords() != 0) { total = searchTotalCount % vo.getNumPerPage() == 0 ? searchTotalCount / vo.getNumPerPage() : searchTotalCount / vo.getNumPerPage() + 1; } pageGrid.setTotal(total); return pageGrid; }
List getPromoterList(BaseConditionVO vo, RowBounds createRowBounds);
<select> select m.uid as id, convert(m.username,char) username, m.realname, m.children_count, m.headimgUrl from members m where m.deleteflag=0 <if>and m.username like CONCAT('%', '${mo.username}', '%')</if> <choose> <when> ORDER BY ${orderField} <if>${orderDirection}</if> </when> <otherwise> order by m.username DESC </otherwise> </choose> </select>
int searchPromoterTotalCount(BaseConditionVO vo);
<select> select count(0) as a from members m where m.deleteflag=0 <if>and m.username like CONCAT('%', '${mo.username}', '%')</if> </select>
protected void out(Object result, HttpServletResponse response) throws IOException { ServletOutputStream out = response.getOutputStream(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.writeValue(out, result); out.flush(); }
Results.prototype.option = function (data) { var option = document.createElement('li'); option.className = 'select2-results__option'; var attrs = { 'role': 'treeitem', 'aria-selected': 'false' }; if (data.disabled) { delete attrs['aria-selected']; attrs['aria-disabled'] = 'true'; } // id为空的情况下,删除的aria-selected,而aria-selected恰好又是列表选中的关键属性。 // 这个就是个坑,只能这么说,select2给出的api上完全不讲这点,我去!!!!!!! if (data.id == null) { delete attrs['aria-selected']; } ...... }
S2.define('select2/data/minimumInputLength',[ ], function () { function MinimumInputLength (decorated, $e, options) { this.minimumInputLength = options.get('minimumInputLength'); // inputMessage this.inputMessage = options.get('inputMessage'); decorated.call(this, $e, options); } MinimumInputLength.prototype.query = function (decorated, params, callback) { params.term = params.term || ''; if (params.term.length Add inputMessage to the defaults in select2.js<p></p><pre class="brush:php;toolbar:false"> this.defaults = { ... minimumInputLength: 0, inputMessage: '', maximumInputLength: 0, ... };
inputTooShort : function(e) { if (e.inputMessage) { return e.inputMessage;// 增加inputMessage } else { var t = e.minimum - e.input.length, n = "请再输入至少" + t + "个字符"; return n } },
Perfectly solve the problem that the input cannot get focus when the BootStrap modal box and select2 are combined
Perfect solution to the failure of loading the select2 framework in the pop-up box under BootStrap
jquery select2 usage experience (recommended)
The above is the detailed content of jQuery plug-in select2 uses ajax to efficiently query large data lists. For more information, please follow other related articles on the PHP Chinese website!