【问题标题】:How to load Json Data into Select2如何将 Json 数据加载到 Select2 中
【发布时间】:2016-10-14 13:18:45
【问题描述】:

我在使用 select2 js 时遇到了问题, 这是我的 json 响应

{"items":[{"name":"majid"}],"total_count":1,"incomplete_results":false}

这是我的 javascript 代码

$(".js-example-data-ajax").select2({
    minimumResultsForSearch: Infinity,
    width: 250,
    //containerCssClass: 'bg-indigo-400',
    //dropdownCssClass: 'bg-indigo-400',
    //containerCssClass: 'select-lg',
    placeholder: "Select a State",
    allowClear: true,
    //tags: true,
    ajax: {
        url:'set',//'https://api.github.com/search/repositories',//'set',
        dataType: 'json',
        delay: 250,
        data: function (params) {
            //alert(params.page);
            return {
                q: params.term//, // search term
                page: params.page
            };
        },
        processResults: function (data, params) {
            // parse the results into the format expected by Select2
            // since we are using custom formatting functions we do not need to
            // alter the remote JSON data, except to indicate that infinite
            // scrolling can be used



            params.page = params.page || 1;

            return {
                results: data.items,
                pagination: {
                    more: (params.page * 30) < data.total_count
                }
            };
        },
        cache: true
    },
    //escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
    minimumInputLength: 1,
    //templateResult: formatRepo, // omitted for brevity, see the source of this page
    //templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});

我不知道我的错误在哪里,我已经阅读了它的示例但找不到任何解决方案, 非常感谢

【问题讨论】:

    标签: javascript json jquery-select2


    【解决方案1】:

    Select 2 接受特定的 JSON 对象结构,即 -

    var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }]; 
    

    在您的情况下,“items”键应包含类似对象的数组,例如[{ id: 1, text: 'bug' }],或者您可以在返回之前修改对象,如下所示 -

    var data = $.map(yourArrayData, function (obj) {
       obj.id = obj.id || obj.pk; // replace pk with your identifier
       return obj;
    });
    

    他们已经在示例代码中添加了以下注释。

    processResults: function (data, params) { 
    // parse the results into the format expected by Select2
    

    查看官方文档 - https://select2.github.io/examples.html#data-array 并阅读此内容 https://select2.github.io/options.html#data

    【讨论】:

    • 感谢您的帮助。
    猜你喜欢
    • 2022-07-07
    • 2018-06-12
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多