我正在使用select2库使用ajax进行下拉。我不能使它工作。这是我的代码:

$("#guests").select2({
        multiple: true,
        minimumInputLength: 1,
        formatInputTooShort: function () {
            return "Enter 1 Character";
        },
        data: function() {
            return data;
        },
        ajax: {
            url: 'some url',
            dataType: 'json',
            processResults: function (data) {
                // 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

                return {
                    results: data.data,
                    pagination: {
                        more: 30
                    }
                }
            }
            /*,
            cache: true*/
        },
        escapeMarkup: function (markup) { return markup; },
        templateResult: formatRepo,
        templateSelection: formatRepoSelection
    })

    function formatRepo (results) {

        var markup = "<div class='select2-result-resultssitory clearfix'>" +
                "<div class='select2-result-resultssitory__avatar'><img src='" + results.id + "' /></div>" +
                "<div class='select2-result-resultssitory__meta'>" +
                "<div class='select2-result-resultssitory__title'>" + results.text + "</div>";

        if (results.description) {
            markup += "<div class='select2-result-resultssitory__description'>" + results.guest_first_name + "</div>";
        }

        markup += "<div class='select2-result-resultssitory__statistics'>" +
                "<div class='select2-result-resultssitory__forks'><i class='fa fa-flash'></i> " + results.guest_last_name + " Forks</div>" +
                "<div class='select2-result-resultssitory__stargazers'><i class='fa fa-star'></i> " + results.guest_do_b + " Stars</div>" +
                "<div class='select2-result-resultssitory__watchers'><i class='fa fa-eye'></i> " + results.text + " Watchers</div>" +
                "</div>" +
                "</div></div>";

        return markup;
    }

    function formatRepoSelection(results) {
        return results.text || results.guest_first_name;
    }


的HTML:


<select id="guests" class="form-control input-guests " data-placeholder="Search guest..." multiple=""></select>


这是我从远程URL获取的JOSN数据:

[{
    "id": 1,
    "guest_first_name": "Jon",
    "guest_last_name": "Doe",
    "guest_do_b": "1954-07-13T00:00:00+0100",
    "text": "Jon Doe"
}, {
    "id": 2,
    "guest_first_name": "Janne",
    "guest_last_name": "Doe",
    "guest_do_b": "1960-01-14T00:00:00+0100",
    "text": "Janne Doe"
}]

最佳答案

有点晚了,但是您的错误是options.results未定义吗?

如果是这种情况,那么您可能想将函数processResults重命名为results

我知道它在带有processResults函数的文档中,但是我遇到了同样的问题,this article为我提供了解决方案。

08-06 04:46