2016-10-14 4 views
0

Я столкнулся с проблемой с помощью ВЫБ.2 JS, Это мой JSON ответитьКак загрузить данные в формате JSON выбор2

{"items":[{"name":"majid"}],"total_count":1,"incomplete_results":false} 

И это мой код Javascript

$(".js-example-data-ajax").select2({ 
    minimumResultsForSearch: Infinity, 
    width: 250, 
    //containerCssClass: 'bg-indigo-400', 
    //dropdownCssClass: 'bg-indigo-400', 
    //containerCssClass: 'select-lg', 
    placeholder: "Select a State", 
    allowClear: true, 
    //tags: true, 
    ajax: { 
     url:'set',//'https://api.github.com/search/repositories',//'set', 
     dataType: 'json', 
     delay: 250, 
     data: function (params) { 
      //alert(params.page); 
      return { 
       q: params.term//, // search term 
       page: params.page 
      }; 
     }, 
     processResults: function (data, params) { 
      // 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 



      params.page = params.page || 1; 

      return { 
       results: data.items, 
       pagination: { 
        more: (params.page * 30) < data.total_count 
       } 
      }; 
     }, 
     cache: true 
    }, 
    //escapeMarkup: function (markup) { return markup; }, // let our custom formatter work 
    minimumInputLength: 1, 
    //templateResult: formatRepo, // omitted for brevity, see the source of this page 
    //templateSelection: formatRepoSelection // omitted for brevity, see the source of this page 
}); 

Я не знаю, где моя ошибка, я прочитал ее примеры, но не нашел никаких решений, Большое спасибо

ответ

1

Выберите 2 принимает определенную структуру объекта JSON ie -

var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }]; 

В вашем случае «элементы» ключ должен содержать массив подобных объектов, как [{ id: 1, text: 'bug' }] или вы можете изменить объект, прежде чем вернуться, как это -

var data = $.map(yourArrayData, function (obj) { 
    obj.id = obj.id || obj.pk; // replace pk with your identifier 
    return obj; 
}); 

Они уже добавили комментарий ниже в их пример кода.

processResults: function (data, params) { 
// parse the results into the format expected by Select2 

Смотреть официальные документы - https://select2.github.io/examples.html#data-array и читать это, а https://select2.github.io/options.html#data.

+0

Благодарим за помощь. –

Смежные вопросы