2015-03-13 17 views
12

Tôi đã đoạn mã sau (javascript):Select2 tải dữ liệu bằng ajax không thể chọn bất kỳ tùy chọn

$('#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); 
    } 
}); 

Đối với phía máy chủ Tôi đang sử dụng ASP MVC 4. Các chọn get dữ liệu sử dụng ajax và đưa ra các tùy chọn nhưng các tùy chọn này không thể chọn được. Đọc bài viết khác, họ mô tả bằng hàm id, nhưng chức năng này appearently desappears vào phiên bản của Select2 Tôi đang sử dụng 2,4

Tôi foolowing ví dụ về ajax trên tài liệu hướng dẫn hiển thị trên github "Đang tải từ xa dữ liệu"

Trả lời

51

Nếu phản ứng ajax của bạn không có idvăn bản thuộc tính bạn nên sửa chữa chúng phía khách hàng

Đây là một yêu cầu về phiên bản 4.0 (không biết tại sao)

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 
        } 
       }; 
      } 

} 
+0

Cảm ơn! đã giúp rất nhiều. – victorkurauchi

+0

Cảm ơn bạn đã giải thích. – KostasC

+0

Hoàn hảo như tôi muốn. Cảm ơn rất nhiều. –

Các vấn đề liên quan