select2 使用 AJAX 加载数据不能选择任何选项

select2 load data using ajax cannot select any option

本文关键字:选择 任何 选项 不能 数据 使用 AJAX 加载 select2      更新时间:2023-09-26

我有以下代码(javascript):

$('#cbxConnections').select2({
    minimumInputLength: 0,
    multiple: false,
    allowClear: true,
    placeholder:{
        text:"@Diccionario.Connections",
        id:" @Diccionario.Connections"
    },
    ajax:{
        url:'@Url.Action("GetActiveConnections","Admin")',
        dataType: 'json',
        type:'post',
        data:function(params){
            return {
                q: params.term
            };
        },
        processResults: function(data,page){
            return {
                results: data
            };
        }
    },
    escapeMarkup: function (markup) { 
        return markup; 
    },
    templateResult: function(response){
        return '<div>'+response.Name+'</div>';
    },
    templateSelection: function(response){
        return response.Id;
    },
    id: function(connection){
       console.log(connection);
    }
});

对于服务器端,我使用的是ASP MVC 4。选择使用 ajax 获取数据并呈现选项,但此选项不可选择。阅读其他帖子,他们描述了使用 id 函数,但这个函数似乎出现在我正在使用 2.4 的 select2 版本上

我正在遵循 github 上显示的文档上的 ajax 示例"加载远程数据"

如果你的ajax响应没有id文本属性,你应该在客户端修复它们

这是 4.0 版的要求(不知道为什么)

ajax: {
   processResults: function (data, params) {
                params.page = params.page || 1;
                // you should map the id and text attributes on version 4.0
                var select2Data = $.map(data.result.data, function (obj) {
                    obj.id = obj._id.$id;
                    obj.text = obj.name;
                    return obj;
                });
                return {
                    results: select2Data,
                    pagination: {
                        more: data.result.more
                    }
                };
            }
 }

我有一个问题,我无法取消选择选项(这是一个选择的倍数),问题是我将id作为数字传递,但它应该是字符串

var select2Data = $.map(data.result.data, function (obj) {
    obj.id = '' + obj._id.$id; //small fix
    obj.text = obj.name;
    return obj;
});
相关文章: