


jQuery plug-in select2 uses ajax to efficiently query large data lists
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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? 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

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

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:

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:

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.

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

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.
