Select2 - Ajax 数据 - 根据查询填充下拉列表

Select2 - Ajax Data - Populate The Dropdown based on query

我正在使用 Select2 来填充英国城镇的下拉列表。由于英国城镇数据库非常庞大,我认为 AJAX 调用是引入数据的最佳方式。

我构建了一个 post 函数和一些 PHP(在 Codeigniter 中)来捕获查询并解析它。

我可以看到数据正在 post 编辑和响应,但是我的 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"}]

我哪里错了?理想情况下,我希望 select 下拉菜单的 select 值 = town_id 和 select 选项是城镇名称。

谢谢。

在您的 ajax 呼叫中,尝试添加 success。像这样:

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

在您的 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
    }
},

因为 select2 想要结果作为具有键 idtext.

的对象数组

否则你已经可以returns一个结构良好的对象

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

然后

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