2016-10-14 3 views
0

Ich habe konfrontiert ein Problem mit select2 js, Das ist mein json reagierenWie JSON-Daten in Select2

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

Und das ist mein Javascript-Code

$(".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 
}); 

Ich weiß nicht laden wo ist mein Fehler, ich habe es gelesen, es ist Beispiele, aber konnte keine Lösungen finden, Vielen Dank

Antwort

1

Wählen Sie 2 akzeptiert eine bestimmte JSON-Objektstruktur ie -

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

In Ihrem Fall „Artikel“ Schlüssel sollte eine Reihe von ähnlichen Objekten wie [{ id: 1, text: 'bug' }] enthalten, oder Sie können das Objekt vor der Rückkehr, wie dies ändern -

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

Sie haben bereits unter Kommentar hinzugefügt in ihrem Beispielcode.

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

Siehe offizielle Dokumentation - https://select2.github.io/examples.html#data-array und lesen Sie diese auch https://select2.github.io/options.html#data.

+0

Vielen Dank für Ihre Hilfe. –