2015-07-19 45 views
0

我在我的项目中使用Select2,但我无法去工作的initselect。我需要用默认值初始化select2。select2 initselection回调ajax - 不加载默认值

这是JS:

​​

PHP页面返回此JSON:

[{"id":"1","text":"1 Programma 1 : Organizzazione E Gestione Servizi Generali"},{"id":"2","text":"2 Programma 2 : Difesa E Sicurezza Del Cittadino"},{"id":"3","text":"3 Programma 3 : Pubblica Istruzione Ed Opportunita' Culturali, Sportive E Ricreative"},{"id":"4","text":"4 Programma 4 : Tutela Dell'ambiente E Gestione Del Territorio E Del Patrimonio"},{"id":"5","text":"5 Programma 5 : Manutenzione Patrimonio Comunale, Viabilità E Trasporti"},{"id":"6","text":"6 Programma 6 : Servizi Alla Persona E Adeguamento Delle Strutture Sociali"},{"id":"7","text":"7 Programma 7 : Servizi Produttivi Ed Interventi Nel Campo Dello Sviluppo Economico"},{"id":"8","text":"8 Programma 8 : Programma Degli Investimenti"}] 

我没有错误的萤火,但选择2 doesen't有任何初始值。 我读了类似的(但不同的问题)在stackoverflow但没有提出的解决方案为我工作。

谢谢你在前进,亲切的问候

回答

0

一些研究,我想出了这个解决方案后:

$('programma_rpp').select2({ 
    placeholder: 'Seleziona..', 
    minimumInputLength: 0, 
    allowClear: true, 
    multiple: false, 
    ajax: { // instead of writing the function to execute the request we use Select2's convenient helper 
     url: 'ajax_select2.php?w=programma_rpp', 
     dataType: 'json', 
     data: function (term) { 
     return { q: term }; //search term 
     }, 
     results: function (data) { 
     return { results: data}; 
     } 
    }, 
    }); 

而对于初始化值我用这个

$('#programma_rpp').select2("data", {"id":"1","text":"1 Programma 1 : Organizzazione E Gestione Servizi Generali"}); 

一切工作正常,我希望它能帮助别人。