[英]Select2 - Ajax Data - Populate The Dropdown based on query
I'm using Select2 to populate a dropdown of UK Towns. 我正在使用Select2来填充UK Towns的下拉列表。 As the UK Towns DB is huge I figured an AJAX call would be the best way to bring in the data. 由于UK Towns DB非常庞大,我认为AJAX调用将是引入数据的最佳方法。
I have built a post function and some PHP (In Codeigniter) to catch the query and parse it. 我建立了一个post函数和一些PHP(在Codeigniter中)来捕获查询并解析它。
I can see the data is being posted and responded, But my Select2 is not populating with the data. 我可以看到数据已发布并得到响应,但是我的Select2没有填充数据。
My jQuery for this is : 我的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
}
);
My response jSON (Example) is as follows : 我的回答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"}]
Where am I going wrong? 我要去哪里错了? I would ideally like the select dropdown to have the select value = town_id and the select option to be the town name. 理想情况下,我希望select下拉列表具有select值= town_id,而select选项则是城镇名称。
Thank You. 谢谢。
in your select2
configuration: 在您的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
wants the results as array of object with keys id
and text
. 因为select2
希望将结果作为键为id
和text
的对象数组。
Otherwise you could already returns a well formed object 否则,您可能已经返回了格式正确的对象
[
{"id":"16994","text":"Hartle"},
{"id":"16995","text":"Hartlebury"},
{"id":"16996","text":"Hartlebury"},
{"id":"16997","text":"Hartlebury Common"}
]
then 然后
results: function (data) {
return {
results: data
}
},
On your ajax call, try adding success . 在您的ajax调用中,尝试添加成功 。 Something like this: 像这样:
success: function( json ) {
$.each(items, function (i, item) {
$('#mySelect').append($('<option>', {
value: item.value,
text : item.text
}));
)};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.