select2 4.0 - 始终向远程数据结果添加选项

select2 4.0 - always add option to remote data results

我将再次升级 3.5 -> 4.0,'almost' 让这个用例像以前一样工作。我现在坚持的是如何始终将某个选项添加到 ajax 结果列表。

这是我现在拥有的:

html:

<select id="vedit-filter" name="settings[filter]" class="form-control select2">
    <option value="default" selected="">default</option>
</select>

js:

$("#vedit-filter").select2({
    placeholder: "Select or enter application...",
    allowClear: true,
    multiple: false,
    tags: true,
    ajax: {
        dataType: 'json',
        delay: 1000,
        type: 'post',
        url: '/process/get_application_list.php',
        data: function (term, page) {
            return {
                term: term, // search term
                page_limit: 25, // page size
                page: page // page number
            };
        },
        results: function (data, page) {
            var more = (page * 25) < data.total; // whether or not there are more results available
            return {
                results: data.results,
                more: more
            };
        }
    }
});

这将加载 'default' 作为初始选择的选项。如果用户更改了它,那么它就消失了。如果需要,我想要一种方法让他们恢复到最初的选择。是将它作为选项包含在我从 ajax 返回的结果中的唯一方法吗?或者有没有办法在js端做到这一点?

更新:

默认选择始终是动态的,但在此示例中我们使用 'default' 的 value/name。

<select id="vedit-filter" name="settings[filter]" class="form-control select2">
    <option value="default" selected="">default</option>
</select>

然后在 js 中:

var default_filter = $("#vedit-filter").val(); //get the default loaded from the html

placeholder: {
  id: default_filter, // or whatever the placeholder value is
  text: default_filter // the text to display as the placeholder
},

我最近 explained this on GitHub 但没有意识到它有多大的破坏性变化。

I want a way for them to revert back to that initial selection if need be.

Select2 提供了 placeholder 选项,如果 selection 尚未生成,它可以让您为用户指定一个占位符,例如 "Select an item"。为了支持 <select>,默认情况下 select 第一个选项(由浏览器完成),Select2 要求 "placeholder" <option> 存在。这也兼作 Select2 用来确定是否需要显示占位符的选项。

除了 placeholder 选项外,Select2 还允许用户删除他们的 selected 选项,这会将 selection 恢复为占位符选项。这可以通过 allowClear 选项启用。

Is the only way to include it in my returned results from ajax as an option? Or is there a way to do this on the js side?

在您的示例中,您使用的是设置了 value 的占位符选项。因为 Select2 默认情况下期望 value 是 blank/empty,所以您需要告诉 Select2 在检测占位符时要查找的内容。这可以通过将数据对象传递到 placeholder 来完成,Select2 在检查时将使用该数据对象。

placeholder: {
  id: 'default', // or whatever the placeholder value is
  text: 'Select or enter application...' // the text to display as the placeholder
}

这将告诉 Select2 在 value 设置为 default 时显示占位符,在您的示例中似乎是 placeholder/default 选项。

What I am stuck on now is how to ALWAYS add a certain option to the ajax results list.

虽然我认为我们可能已经解决了 the XY problem here,但我确实想指出,向 AJAX 结果列表添加一个新选项就像覆盖 processResults 一样简单。这是因为 processResults 将数据对象列表直接传递给 Select2,这为您提供了一个向列表中注入新选项的安全位置。

您只需要将额外的数据对象 .push 放入 results,然后将它们传递回 Select2。