经过几个小时,我终于得到了json文件加载并正确显示,包括使用Select2 4.0的标志图标,看看代码看起来多么简单是荒谬的。
但是现在,由于某些原因,搜索功能无效。我无法搜索任何选项。
希望它快速而简单,我可以在头脑中因为没有早点发现它。
HTML:
<select id="country_select" class="form-control"></select>
JS:
<script>
function formatCountry (country) {
if (!country.id) { return country.text; }
var $country = $(
'<span><img src="/assets/img/flags/' + country.code.toLowerCase() + '.png" class="flag" /> ' + country.text + '</span>'
);
return $country;
};
$('#country_select').select2({
templateResult: formatCountry,
templateSelection: formatCountry,
ajax: {
url: '/assets/json/countries.json',
dataType: 'json',
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, page) {
return {
results: $.map(data, function(country) {
return { id: country.id, code: country.code, text: country.name };
})
};
}
}
});
</script>
JSON:
{
"id":53,
"code":"CW",
"name":"Curaçao",
"iso_alpha_3":"CUW",
"iso_numeric":531
},
{
"id":54,
"code":"CX",
"name":"Christmasøya",
"iso_alpha_3":"CXR",
"iso_numeric":162
},
{
"id":55,
"code":"CY",
"name":"Kypros",
"iso_alpha_3":"CYP",
"iso_numeric":196
},
答案 0 :(得分:0)
Select2期望您的结果将在服务器端进行过滤,因此在使用AJAX时它不会自行匹配。
鉴于您的JSON是静态的,我建议您使用$.ajax
预先加载它,然后使用data
选项代替ajax
将其加载到Select2中。