Select2通过Ajax加载JSON数据后搜索无返回结果问题排查
问题原因
- Select2的AJAX模式默认采用服务端搜索逻辑:会将用户输入的搜索词作为
q参数传递给接口,且默认不会在客户端对返回结果做二次匹配,认为接口返回的就是过滤后的匹配结果。 - 你使用静态JSON文件作为数据源,无法根据传入的搜索参数返回过滤后的数据,因此搜索功能无法正常生效。
- 你当前配置的
tokenSeparators参数仅适用于多选场景,单选select不需要该配置,也可能引发异常。
解决方案
方案一(更推荐):提前加载全量数据再初始化Select2
静态数据不需要使用AJAX模式,先拉取全量数据后直接通过data属性传入组件即可,默认自带客户端搜索能力:
<html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js" ></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script> <script> jQuery(document).ready(function() { // 先请求全量国家数据 $.getJSON('countries2.json', function(res) { $('#allowedCountries').select2({ placeholder: 'Select allowed countries', allowClear: true, data: res.results }); }) }); </script> </head> <body> for select2<br> <div style="width:100%"> <select name="allowedCountries" class="js-states form-control" id="allowedCountries"><option></option></select> </div> </body> </html>
方案二:保留AJAX模式,新增客户端匹配配置
如果必须使用AJAX模式,需要配置matcher开启客户端匹配,同时清空多余的请求参数:
jQuery(document).ready(function() { $('#allowedCountries').select2({ placeholder: 'Select allowed countries', allowClear:true, ajax: { dataType : "json", url: "countries2.json", // 清空默认传递的搜索参数,避免静态文件请求异常 data: function(params) { return {} }, // 缓存全量数据,避免重复请求 cache: true }, // 配置客户端匹配器,对返回的全量结果做搜索匹配 matcher: function(params, data) { if ($.trim(params.term) === '') { return data; } if (typeof data.text === 'undefined') { return null; } if (data.text.toLowerCase().indexOf(params.term.toLowerCase()) > -1) { return $.extend({}, data, true); } return null; } }); });
内容的提问来源于stack exchange,提问作者i need help
相关产品推荐
相关产品推荐

