Home > Web Front-end > JS Tutorial > body text

jQuery plug-in select2 uses ajax to efficiently query large data lists

小云云
Release: 2018-01-11 14:33:38
Original
4655 people have browsed it

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

jQuery plug-in select2 uses ajax to efficiently query large data lists
jQuery plug-in select2 uses ajax to efficiently query large data lists
jQuery plug-in select2 uses ajax to efficiently query large data lists

##Local actual results

jQuery plug-in select2 uses ajax to efficiently query large data lists

2. Import css and js to the website

1. Use CDN to save the traffic of your website

<link>
<script></script>
Copy after login
2. Download the file locally, you can Make some personalized customizations (such as modifying prompts)

git download address


<link>
<script></script>

<script></script>
Copy after login
3. Do it with real swords and guns

The first step is to customize the page personality ized element

<select>
 <option>沉默王二</option>
</select>
Copy after login
The Java side can obtain the value of select through the name attribute.

Set class to js-data-example-ajax, and initialize select2 of the component when the page is loaded.

The href attribute provides the URL for background retrieval by ajax.

style sets the width of the component.

The inputMessage attribute customizes personalized prompts. The default English version is Please enter 1 or more characters, and the Chinese international version is "Please enter at least 1 more characters". Neither of them can meet the personalized needs. Therefore, it needs to be changed, which will be introduced later.

Provide a default option, which is displayed before the page is retrieved.

The second step is to componentize select2, and the comments are very detailed

<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 : &#39;json&#39;,
     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=&#39;select2-result-repository clearfix&#39;>" + "<p class=&#39;select2-result-repository__avatar&#39;><img src=&#39;"
       + repo.headimgUrl + "&#39; />" + "<p class=&#39;select2-result-repository__meta&#39;>"
       + "<p class=&#39;select2-result-repository__title&#39;>" + repo.username + "";
     if (repo.realname) {
      markup += "<p class=&#39;select2-result-repository__description&#39;>" + repo.realname + "";
     }
     markup += "<p class=&#39;select2-result-repository__statistics&#39;>"
       + "<p class=&#39;select2-result-repository__forks&#39;><i class=&#39;fa fa-user&#39;> 下级会员数" + repo.children_count + " "
       + "" + "";
     return markup;
    }, 
    templateSelection : function(repo) {
     return repo.realname || repo.text;
    }// 列表中选择某一项后显示到文本框的内容
   });
  });
 });
</script>
Copy after login
The third step is to receive the parameters on the Java side and return the result set. I don’t need to emphasize that this step is very important

@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);
}
Copy after login
Next, post the key source code. It may not match your project, but it can be used as a reference.

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>
Copy after login
selec2 paging and Java-side paging parameters match

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;
}
Copy after login
Data encapsulation from Java end to select2 end

@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;
 }
}
Copy after login
The data source obtained by MySQL is converted and matched with PageGrid

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;
}
Copy after login
Mybatis’ paging is super simple. As long as createRowBounds is set, mybatis will automatically paginate for you. This is amazing.

List getPromoterList(BaseConditionVO vo, RowBounds createRowBounds);
Copy after login
sql statement, the key point here is that the id (m.uid as id) must be returned to select2.

<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>
Copy after login
Have you not seen the paging limit of mysql? Well, here No need to pay attention, this is what the framework does for us.

Total number

int searchPromoterTotalCount(BaseConditionVO vo);
Copy after login
count(0) is fine

<select>
 select count(0) as a
 from
 members m
 where m.deleteflag=0 
 <if>and m.username like CONCAT('%', '${mo.username}', '%')</if>
</select>
Copy after login
output to the response

protected void out(Object result, HttpServletResponse response) throws IOException {
 ServletOutputStream out = response.getOutputStream();
 ObjectMapper objectMapper = new ObjectMapper();
 objectMapper.writeValue(out, result);
 out.flush();
}
Copy after login
At this point, the remote function of select2 is in the code part Completely posted.

However, I still want to emphasize a few points in the end:

1. The paging parameters Java side and select2 must be compared.

2. The returned data must be passed back with an ID, otherwise the returned list cannot be selected. Why? You can find out by investigating the source code of select2.

 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'];
 }
 ......
}
Copy after login
3. How to obtain the value of select2 in the form? The answer is, 1. The returned result set must have an id, and 2. The input tag must have a name attribute.

4. How to customize inputMessage?

Find the following code in select2.js, pay attention to the comment part

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,
  ...
 };
Copy after login
and then add it to the zh-CN.js file Modify the inputTooShort method

inputTooShort : function(e) {
 if (e.inputMessage) {
  return e.inputMessage;// 增加inputMessage
 } else {
  var t = e.minimum - e.input.length, n = "请再输入至少" + t + "个字符";
  return n
 }
},
Copy after login
Related recommendations:


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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template