【问题标题】:Select2 AJAX TagsSelect2 AJAX 标签
【发布时间】:2023-03-13 12:01:02
【问题描述】:

我有以下 JSON,通过 /tags 检索到:

[
    {
        "id": "CSS",
        "text": "CSS"
    },
    {
        "id": "HTML",
        "text": "HTML"
    },
    {
        "id": "JavaScript",
        "text": "JavaScript"
    },
    {
        "id": "jQuery",
        "text": "jQuery"
    },
    {
        "id": "MySQL",
        "text": "MySQL"
    },
    {
        "id": "PHP",
        "text": "PHP"
    }
]

我有一个<input />,它通过使用 Select2 来接受标签:

<input name="Tags" id="Tags" value="PHP,HTML,jQuery" />

我以这种方式附加了 Select2:

$("#Tags").select2({
    tags: true,
    tokenSeparators: [",", " "],
    createSearchChoice: function(term, data) {
        if ($(data).filter(function() {
            return this.text.localeCompare(term) === 0;
        }).length === 0) {
            return {
                id: term,
                text: term
            };
        }
    },
    multiple: true,
    ajax: {
        url: '/tags',
        dataType: "json",
        data: function(term, page) {
            return {
                q: term
            };
        },
        results: function(data, page) {
            return {
                results: data
            };
        }
    }
});

问题

  1. 当我加载页面时,默认值会消失。
  2. Select2 向/tags 发出请求,但它不加载标签。

控制台中也没有错误。我正在使用 CDN 中的 Select2 3.5.2。我哪里错了?

【问题讨论】:

  • “默认值关闭”和“它不加载标签”是什么意思? Select2 是否显示任何内容?
  • @KevinBrown 是的...默认值将丢失。

标签: javascript jquery ajax tags jquery-select2


【解决方案1】:

嗯,我用过这个。看起来像是破解或变通方法。

$("#Tags").select2({
    tags: true,
    multiple: true
});
$.getJSON("/tags", function (data) {
    if (data.length > 0)
        $("#Tags").select2({
            tags: data,
            multiple: true
        });
});

希望这对某人有所帮助。在我得到更好的建议之前,我会一直保持开放状态。

【讨论】:

    猜你喜欢
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 2013-01-23
    • 2014-02-18
    相关资源
    最近更新 更多