簡體   English   中英

select2 加載數據使用 ajax 不能 select 任何選項

[英]select2 load data using ajax cannot select any option

我有以下代碼(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。 select 使用 ajax 獲取數據並呈現選項,但此選項不可選擇。 閱讀其他帖子,他們描述了使用 id function,但是這個 function 在我使用的 select2 版本上似乎消失了 2.4

我正在關注github “加載遠程數據”上顯示的文檔中 ajax 的示例

如果你的ajax響應沒有idtext屬性,你應該修復它們的客戶端

這是版本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
                    }
                };
            }

 }

我有一個問題,我無法取消選擇選項(它是 select 倍數),問題是我將 id 作為數字傳遞,但它應該是字符串

var select2Data = $.map(data.result.data, function (obj) {
    obj.id = '' + obj._id.$id; //small fix
    obj.text = obj.name;

    return obj;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM