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

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

Jan 11, 2018 pm 02:33 PM
ajax jquery

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

See all articles