简体   繁体   English

select2 initselection回调Ajax-不加载默认值

[英]select2 initselection callback ajax - not loading default value

i'm using Select2 in my project, but i can't get to work the initselect. 我在我的项目中使用Select2,但是我无法使用initselect。 I need to initialize the select2 with a default value. 我需要使用默认值初始化select2。

this is the js: 这是js:

function format(item) { return item.text; }
var jresults;
    $.getJSON("ajax_select2.php?w=programma_rpp").done(
        function( data ) {
            $.jresults = data;
            $("#programma_rpp").select2({
                  placeholder: "Seleziona un opzione",
                  allowClear: true,
                  formatResult: format,
                  formatSelection: format,
                  data: $.jresults,
                  initSelection: function (element, callback) {
                    callback({id: '1', text: 'testtext' });
                }
              }
            );
        }
    )

The php page return this json: 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"}]

I got no error in firebug but the select2 doesen't have any initial value. 我在萤火虫中没有任何错误,但select2没有任何初始值。 I read similar (but different somehow) problems on stackoverflow but none of the proposed solution work for me. 我在stackoverflow上读到了类似(但有所不同)的问题,但所提出的解决方案均不适用于我。

Thank you in advance, kind regards 预先谢谢你,亲切的问候

After some research i come up with this solution: 经过研究,我提出了以下解决方案:

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

And for initialize the value i use this 为了初始化值,我用这个

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

All works fine, i hope it can help someone else. 一切正常,我希望它可以帮助其他人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM