如何将选择 2 加载远程数据与初始选择混合使用

How to mix Select 2 Loading Remote Data with Initial Selections

本文关键字:选择 混合 数据 加载 程数据      更新时间:2023-09-26

https://select2.github.io/examples.html#data-ajax

对于 select2,我想:

  1. 列出一些初始选择,所以对于小列表,我们可以直接选择它。
  2. 远程搜索长/更多选择。

但是,我似乎无法同时提供ajaxdata参数。

有什么建议吗?谢谢。


添加了代码片段

function installShopSelect2() {
    var url = "/ajax/brandEnterprise/findShops.mapi";
    "use strict";
    $('#shopid').select2({
        ajax: {
            type: "GET",
            url: url,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            delay: 250,
            //async: false,
            data: function (params) {
                return {
                    keyword: params.term,
                    besId: selectedBes,
                    page: params.page
                };
            },
            processResults: function (data, params) {
                // parse the results into the format expected by Select2
                // since we are using custom formatting functions we do not need to
                // alter the remote JSON data, except to indicate that infinite
                // scrolling can be used
                params.page = params.page || 1;
                return {
                    results: data,
                    pagination: {
                        more: (params.page * 30) < data.total_count
                    }
                };
            },
            cache: true
        },
        escapeMarkup: function (markup) {
            return markup;
        },
        //data: $.getJSON(url, {besId: selectedBes, keyword: ''}, function (data) {
        //    return {results: data};
        //}),
        placeholder: "--Please search--",
        minimumInputLength: 2,
        allowClear: true
    });
}

我解决这个问题的方法是设置 minimumInputLength=0,编写一个自定义 ajax 传输器来检查搜索词的长度,当它等于 0 时,我使用固定的默认值调用成功回调,否则如果大于 0,我只执行 ajax 调用并返回响应。