javascript - select2 4.0 AJAX 预填充方法?

标签 javascript jquery json ajax jquery-select2

我已经读过 this , this , this并根据文档 the most important here ,但它们都不适合我。 我正在尝试使用 AJAX select2。我正在尝试制作一个通用的“选择”项目。

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

$('[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
    });
});

效果很好!

works well

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

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

它非常接近您的 AJAX 示例 can find in the documentation .我的问题是 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({.. above )但这不起作用并给我空白值:

blank value

注意:the solution here given by Kevin Brown也不起作用,给我完全相同的结果。

另一种解决方案是在 AJAX 中使用类似“&init=1”(或类似的东西)的参数请求 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;
}

最佳答案

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

<select multiple="multiple" ...

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

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

如果您看一下 fiddle ,您会发现它按照您希望的方式工作。

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

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

虽然我不知道你的formatRepoSelection代码是什么,但我想如果你把它改成类似下面的代码,你的问题就会得到解决:

function formatRepoSelection(repo) {
  return repo.item;
}

关于javascript - select2 4.0 AJAX 预填充方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34405690/

相关文章:

Javascript - 计算当前日期 1 年/3 个月/1 个月前的日期 (dd-mm-yyyy)

json - 具有默认参数的通用案例类的 Circe 编码器

具有 native JSON 支持的 MySQL 5.7 - 如何选择数组中存在特定值的行?

JSON Schema oneOf 属性已填充

javascript - data = null时如何打印空

jquery - 让 jqGrid 填充其容器

jquery.maskedinput 以编程方式设置值并应用掩码?

回调中的 JavaScript 作用域

javascript - CSV 解析器文档

javascript - 如何在 javascript 中递归使用 reduce() 方法?