【问题标题】:Select2 4.0 JSON search not workingSelect2 4.0 JSON 搜索不起作用
【发布时间】:2015-09-11 09:12:47
【问题描述】:

几个小时后,我终于让 json 文件加载并正确显示,包括使用 Select2 4.0 的标志图标,看看代码看起来多么简单,这很荒谬。

但是现在,由于某种原因,搜索功能无法正常工作。我无法搜索任何选项。

希望它既快速又简单,而且我可以打自己的头,因为没有早点发现它。

HTML:

<select id="country_select" class="form-control"></select>

JS:

<script>
        function formatCountry (country) {
            if (!country.id) { return country.text; }
            var $country = $(
                    '<span><img src="/assets/img/flags/' + country.code.toLowerCase() + '.png" class="flag" /> ' + country.text + '</span>'
            );
            return $country;
        };

        $('#country_select').select2({
            templateResult: formatCountry,
            templateSelection: formatCountry,
            ajax: {
                url: '/assets/json/countries.json',
                dataType: 'json',
                data: function (params) {
                    return {
                        q: params.term,
                        page: params.page
                    };
                },
                processResults: function (data, page) {
                    return {
                        results: $.map(data, function(country) {
                            return { id: country.id, code: country.code, text: country.name };
                        })
                    };
                }
            }
        });

    </script>

JSON:

{
"id":53,
"code":"CW",
"name":"Curaçao",
"iso_alpha_3":"CUW",
"iso_numeric":531
},
{
"id":54,
"code":"CX",
"name":"Christmasøya",
"iso_alpha_3":"CXR",
"iso_numeric":162
},
{
"id":55,
"code":"CY",
"name":"Kypros",
"iso_alpha_3":"CYP",
"iso_numeric":196
},

【问题讨论】:

  • json和html是什么样子的
  • 我用 JSON 更新了,HTML 已经存在了。我已经在没有任何 CSS 并加载相同数据的小提琴上进行了尝试,但在那里搜索也不起作用。

标签: javascript jquery json jquery-select2


【解决方案1】:

Select2 期望您的结果将在服务器端进行过滤,因此在使用 AJAX 时它不会自行进行任何匹配。

鉴于您的 JSON 是静态的,我建议您只使用 $.ajax 预加载它,然后使用 data 选项而不是 ajax 将其加载到 Select2 中。

【讨论】:

    猜你喜欢
    • 2015-10-12
    • 2013-02-04
    • 2016-10-24
    • 1970-01-01
    • 2016-03-17
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多