Home  >  Article  >  Web Front-end  >  jQuery plug-in select2 uses ajax to efficiently query large data lists

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

小云云
小云云Original
2018-01-11 14:33:384507browse

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


2. Download the file locally, you can Make some personalized customizations (such as modifying prompts)

git download address





3. Do it with real swords and guns

The first step is to customize the page personality ized element

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

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);
}
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 mo = new HashMap();
 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 getMo() {
  return mo;
 }
 /**
  * @param mo
  *   the mo to set
  */
 public void setMo(Map mo) {
  this.mo = mo;
 }
}
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;
}
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;
 }
}
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;
}
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);
sql statement, the key point here is that the id (m.uid as id) must be returned to select2.

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);
count(0) is fine

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();
}
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'];
 }
 ......
}
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

 this.defaults = {
 ...
  minimumInputLength: 0,
  inputMessage: '',
  maximumInputLength: 0,
  ...
 };
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
 }
},
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!

Statement:
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