我使用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和選擇選項是城鎮名稱。
謝謝。
我只想指出,在4.0.0中,我們已將'results'重命名爲'processResults',但仍然適用相同的想法(您需要'id'和'text'鍵)。 –
是的。新規格需要'processResults'。 –