【问题标题】:Select2 4.0.0 not supporting tagging, not able to get tags items through ajax callSelect2 4.0.0 不支持标记,无法通过ajax调用获取标记项
【发布时间】:2018-06-12 03:16:11
【问题描述】:

我无法使用 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 };
        }
    }
  });

【问题讨论】:

    标签: jquery ajax jquery-select2 tagging jquery-select2-4


    【解决方案1】:

    使用 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/

    【讨论】:

      猜你喜欢
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-22
      • 2012-09-02
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多