2017-03-01 42 views
1

我是AJAX的新手,我試圖從select2的AJAX請求中獲得結果。如何讓使用select2的AJAX工作?

這是我的HTML:

<select class="js-example-basic-single" name="Airport"><option disabled selected>Airport</option></select> 

,這是我選擇2呼叫:

$(function() { 
    initAirportList = function(){ 
     $(".js-example-basic-single").select2({ 
      // minimumInputLength: 2, 
      ajax: { 
      dataType: 'json', 
      type: "GET", 
      url: 'data', 
      delay: 250, 
      } 
     ,}); 
    } 

    initAirportList(); 
}); 

JSON數據是在這裏:

[ 
{id:'ADL',text:'Adelaide, Australia, ADL'}, 
{id:'MEL',text:'Melbourne, Australia, MEL'}, 
{id:'PER',text:'Perth, Australia, PER'}, 
{id:'SYD',text:'Sydney, Australia, SYD'} 
] 

我要補充什麼成代碼select2開始顯示結果?

謝謝!

回答

0

首先看看文檔。介紹瞭如何從遠程資源加載數據。

https://select2.github.io/examples.html#data-ajax

https://select2.github.io/options.html#ajax

我想,你缺少在初始化一些選項。 您必須添加data選項,您ajax要求:

ajax: { 
     dataType: 'json', 
     type: "GET", 
     url: 'data', 
     delay: 250, 
     data: function (params) { 
      return { 
       q: params.term, // search term 
       page: params.page 
      }; 
     } 
+0

感謝您的回覆!我真的不明白他們想要做什麼來聲明這個'data'和'processResults'參數。我看到,當我點擊「選擇」框時,接收到「json」數據。但我不明白如何檢索它們?如果沒有'ajax',選擇框完美地工作。 –