5

我已经阅读了 thisthisthis以及根据文档最重要的 here,但它们都不适合我。我正在尝试使用 AJAX select2。我正在尝试制作一个通用的“选择”项目。

因此,对于所有具有data-select2-json属性的元素,我将 aselect2data-select2-json值中的 ajax URL 一起应用。

$('[data-select2-json!=""][data-select2-json]').each(function() {
    var url = $(this).attr('data-select2-json');
    var pg_size = $(this).attr('data-select2-page-size') | 30;
    $(this).select2({
        language: language_code,
        tokenSeparators: [',', ' '],
        ajax: {
            url: url,
            dataType: 'json',
            delay: 300,
            data: function (params) {
                return {
                    q: params.term, // -> q=[search term]
                    page: params.page // -> page=[no page]
                };
            },
            processResults: function (data, params) {
                params.page = params.page || 1;
                console.log(data.items);
                return {
                    results: data.items,
                    pagination: {
                      more: (params.page * pg_size) < data.total
                    }
                };
            },
            cache: true
        },
        // let our custom formatter work
        escapeMarkup: function (markup) { return markup; },
        minimumInputLength: 1,
        templateResult: formatRepo,
        templateSelection: formatRepoSelection
    });
});

它运作良好!

效果很好

服务器发送的 JSON 格式始终如下:

{"items":
    [{"item": "Fran\u00e7ais", "id": 1},
     {"item": "Finlandais", "id": 5},
     {"item": "Chinois simplifi\u00e9", "id": 15}
    ],
"total": 3}

它非常接近您可以在文档中找到的 AJAX 示例。我的问题是 AJAX 初始化:我想在 HTML 中添加值:

<select multiple="multiple" class="form-control"
        data-select2-json="/fr/chez-moi/tags/langues"
        multiple="multiple"
        name="known_languages">
    <option value="1" selected="selected">Français</option>
    <option value="2" selected="selected">Chinois simplifié</option>
</select>

然后用 select2 (=$(this).select2({..上面的代码)初始化,但这不起作用并给我空白值:

空白值

注意:Kevin Brown 给出的解决方案也不起作用,并且给了我完全相同的结果。

&init=1另一种解决方案是在 AJAX 中使用诸如“ ”(或类似的东西)之类的参数向 URL 询问,以便服务器将发送带有附加参数的结果,例如checked: true每个值,我将select2使用这些值进行调用。

文档中没有明确说明如何预填充select2. 我应该怎么做?

这是我的其他功能:

function item_or_text(obj) {
    if (typeof(obj.item)!='undefined') {
        return (obj.item.length ? obj.item : obj.text);
    }
    return obj.text;
}

function formatRepo(data) {
    if (data.loading) return data.text;
    var markup = item_or_text(data);
    console.log('formatRepo', data, markup);
    return markup;
}

function formatRepoSelection(item) {
    var retour = item_or_text(item);
    console.log('formatRepoSelection', item, item.item, retour);
    return retour;
}
4

2 回答 2

3

我使用Select2 示例页面上提供的示例代码在 jsfiddle 上创建了一个工作示例。我只需要更改他们的示例选择标签以接受多个像您这样的标签:

<select multiple="multiple" ...

我还添加了第二个默认选择选项:

<option value="3620194" selected="selected">select2/select2</option>
<option value="317757" selected="selected">Modernizr/Modernizr</option>

如果你看一下小提琴,你会看到它按照你希望的方式工作。

您没有包含您的templateSelection: formatRepoSelection方法的代码。我的猜测是该方法是您的问题的原因。示例页面上使用的代码是:

function formatRepoSelection(repo) {
  return repo.full_name || repo.text;
}

虽然我不知道您的formatRepoSelection代码是什么,但我认为如果您将其更改为以下内容,您的问题将得到解决:

function formatRepoSelection(repo) {
  return repo.item;
}
于 2015-12-22T04:27:46.560 回答
0

我解决这个问题如下:就在选择元素上执行 select2() 之前,获取它的初始值:

var initval = selector.attr("value");

将其转换为 select2 后,使用 initval 创建一个选项:

if (initval) {
    var option = new Option(initval, initval, true, true);
    selector.append(option).trigger('change');
}

您可以对多值选择元素执行类似的操作。

于 2018-08-03T08:53:01.070 回答