Select2 4.0.0 不支持标记,无法通过 ajax 调用获取标记项



我无法使用 select2 版本 4.0 来开发一个选项,在写入所需标签名称的几个字母(2,3 个字母(后,通过 ajax 调用建议存储在数据库中的标签项目。

由于版本initSelection更改,以前版本的方法不再存在。它"No select2/compat/initSelection".

错误

以下是我在以前版本中使用的代码:

 $('.addTags').select2({
    placeholder: "Problem Tags",
    allowClear: true,
    minimumInputLength: 2,
    tags: true,
    createSearchChoice: function (term, data) {
        if ($(data).filter(function () {
            return this.text.localeCompare(term) === 0;
        }).length === 0) {
            return {
                id: term,
                text: term
            };
        }
    },
    initSelection: function (element, callback) {
        var tags = element.val().split(",");
        var data = [];
        for (var i = 0; i < tags.length; i++) {
            data.push({ id: tags[i], text: tags[i] });
        }
        callback(data);
    },
    multiple: true,
    ajax: { 
        type: 'GET',
        url: "/Problem/GetTags",
        dataType: 'json',
        data: function (term, page) {
            return {
                term: term, 
                page_limit: 15
            };
        },
        results: function (data, page) { 
            return { results: data.tags };
        }
    }
  });

使用 Select2 4.0.0 版本时,您必须将createSearchChoice更改为createTag

createTag: function (params) {
    var term = $.trim(params.term);
    if (term === '') {
      return null;
    }
    return {
      id: term,
      text: term,
      newTag: true // add additional parameters
    }
}

那么通常不需要initSelection(见 https://select2.org/upgrading/migrating-from-35#removed-the-requirement-of-initselection(。

在 ajax 选项中results处理程序更改为processResults

processResults: function (data, page) { 
    return { results: data.tags };
},

例如,这是一个jsfiddle:https://jsfiddle.net/beaver71/bhodkpav/

最新更新