我如何将值预加载到Select2控件中并仍然搜索远程数据?

问题描述 投票:2回答:1

当我将值预加载到Select2下拉列表中时,展开控件以键入一个值。它过滤预加载的值。在文本框中键入文字时,如何配置Select2以进行Ajax调用(新搜索)?如果我不将值预加载到Select2中,则ajax调用会起作用。那我怎么都可以呢?

我向select2控件预加载类似这样的内容:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: url,
    data: json,
    dataType: "json",
    success: function (data, textStatus) {
        var json = JSON.parse(data.d);
        var arrData = [];
        if (json !== null && json !== undefined) {
            if (json.length > 0) {
                $.each(json, function (index, element) {
                    var item = { id: element.CommonName, text: element.CommonName, name: element.CommonName };
                    arrData.push(item);
                });
            }
        }
        $("[ID$=ddlDropDown]").select2({
            data: arrData
        });
    }
});

我用这个实例化我的Select2控件:

$("[ID$=ddlDropDown]").select2({
    ajax: {
        url: url,
        type: "POST",
        dataType: 'json',
        async: true,
        contentType: "application/json; charset=utf-8",
        delay: 500,
        data: function (params) {

                var query = {
                    searchString: (params.term || ""),
                    page: params.page
                }
                // Query paramters will be ?search=[term]&page=[page]
                return JSON.stringify(query);


        },
        processResults: function (data, page) {
            var json = JSON.parse(data.d);
            if (json != null) {
                if (json.length > 0) {
                    return {
                        results: $.map(json, function (item) {
                            return {
                                text: item.CommonName,
                                name: item.CommonName,
                                id: item.CommonName
                            }
                        })
                    };
                } else {
                    return false;
                }
            }
            else {
                return false;
            }

        },
        success: function (data, page) {
            $("[ID$=ddlDropDown]").select2("data", data, true);
        }
    },
    minimumInputLength: 2,
    placeholder: "Select a Value",
    disabled: false,
    cache: true
});
javascript jquery jquery-select2 select2
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.