Stu*_*ett 0 php jquery codeigniter jquery-select2
我正在使用Select2来填充英国城镇的下拉列表.由于英国城镇数据库庞大,我认为AJAX调用将是引入数据的最佳方式.
我已经构建了一个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
}
);
Run Code Online (Sandbox Code Playgroud)
我的回复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"}]
Run Code Online (Sandbox Code Playgroud)
我哪里错了?理想情况下,我希望选择下拉列表的选择值= town_id,并选择选项作为城镇名称.
谢谢.
在您的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
}
},
Run Code Online (Sandbox Code Playgroud)
becasue select2希望结果作为对象的阵列的键id和text.
否则你可能已经返回一个格式良好的对象
[
{"id":"16994","text":"Hartle"},
{"id":"16995","text":"Hartlebury"},
{"id":"16996","text":"Hartlebury"},
{"id":"16997","text":"Hartlebury Common"}
]
Run Code Online (Sandbox Code Playgroud)
然后
results: function (data) {
return {
results: data
}
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4978 次 |
| 最近记录: |