2015-04-29 64 views
0

我使用Select2填充英國城鎮的下拉菜單。由於英國Towns DB非常龐大,我認爲AJAX呼叫將是引入數據的最佳方式。Select2 - Ajax Data - 基於查詢填充下拉列表

我已經構建了一個post函數和一些PHP(在Codeigniter中)來捕獲查詢並解析它。

我可以看到數據正在發佈和響應,但我的Select2沒有填充數據。

我給這jQuery是:

$("#areas").select2(
    { 
     tags: [], 
     ajax: { 
      url: '/profile/get-towns', 
      dataType: 'json', 
      type: "POST", 
      quietMillis: 100, 
      data: function (term) { 
       return { 
        query: term 
       }; 
      }, 
      results: function (data) { 
       return { 
        results: data.town_id 
       } 
      }, 
      cache: true 
     }, 
     escapeMarkup: function (markup) { return markup; }, // let our custom formatter work 
     minimumInputLength: 4, 
     placeholder   : "Start typing your Town/City", 
     maximumSelectionSize: 2 
    } 
); 

我的回答是JSON(例)如下:

[{"town_id":"16994","town":"Hartle"},{"town_id":"16995","town":"Hartlebury"},{"town_id":"16996","town" 
:"Hartlebury"},{"town_id":"16997","town":"Hartlebury Common"},{"town_id":"16998","town":"Hartlepool" 
},{"town_id":"16999","town":"Hartley"},{"town_id":"17000","town":"Hartley"},{"town_id":"17001","town" 
:"Hartley"},{"town_id":"17002","town":"Hartley"},{"town_id":"17003","town":"Hartley Green"},{"town_id" 
:"17004","town":"Hartley Green"},{"town_id":"17005","town":"Hartley Mauditt"},{"town_id":"17006","town" 
:"Hartley Wespall"},{"town_id":"17007","town":"Hartley Wintney"},{"town_id":"27051","town":"New Hartley" 
},{"town_id":"35891","town":"Stowe-by-Chartley"}] 

我要去哪裏錯了?我希望喜歡選擇下拉列表中選擇值= town_id和選擇選項是城鎮名稱。

謝謝。

回答

5
select2配置

results: function (data) { 
    var res = []; 
    for(var i = 0 ; i < data.length; i++) { 
     res.push({id:data[i].town_id, text:data[i].town}); 
    } 
    return { 
     results: res 
    } 
}, 

becasue select2希望結果作爲對象的數組鍵idtext

否則你可能已經返回以及形成對象

[ 
    {"id":"16994","text":"Hartle"}, 
    {"id":"16995","text":"Hartlebury"}, 
    {"id":"16996","text":"Hartlebury"}, 
    {"id":"16997","text":"Hartlebury Common"} 
] 

然後

results: function (data) { 
    return { 
     results: data 
    } 
}, 
+2

我只想指出,在4.0.0中,我們已將'results'重命名爲'processResults',但仍然適用相同的想法(您需要'id'和'text'鍵)。 –

+0

是的。新規格需要'processResults'。 –

0

在您的ajax電話上,嘗試加入成功。事情是這樣的:

success: function(json) { 
    $.each(items, function (i, item) { 
     $('#mySelect').append($('<option>', { 
      value: item.value, 
      text : item.text 
     })); 
    )}; 
} 
+0

嗨,成功函數似乎並沒有與選擇2工作。 – StuBlackett

+0

在成功funcion中,只需添加一個警報或日誌來檢查「json」對象是否返回數據。它應該打印數據。如果它返回,則問題在於追加。讓我知道 –

+1

Select2提供了自己的「成功」處理程序(OP使用),不需要繞過Select2如何生成結果。 –