以防万一像我这样的人遇到这种情况,Select2 v4 手册为此提供了答案:https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2
以下 sn-p 来自文档。本质上,您通过 ajax 调用获取初始值,并通过select2:select 事件以编程方式设置初始值。
// Set up the Select2 control
$('#mySelect2').select2({
ajax: {
url: '/api/students'
}
});
// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
type: 'GET',
url: '/api/students/s/' + studentId
}).then(function (data) {
// create the option and append to Select2
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
studentSelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
但是,如果您使用 templateSelection 选项,并返回一个 jQuery 对象以提供花哨的单行格式选择结果,则此解决方案将不起作用。事实上,触发 select2:select 似乎什么也没做。
使用 jQuery,我发现我可以将数据附加到选项,并从 templateSelection 函数中,将此数据用作后备。
// create the option and append to Select2
var option = new Option(data.full_name, data.id, true, true);
$(option).data('raw', data);
studentSelect.append(option).trigger('change')
并且在templateSelection函数中:
templateSelection: function (result) {
if (!result.id || result.loading) {
return result.text
}
var $container = $(
'<div class="clearfix">' +
'<div class="pull-left select2-result__name"></div>' +
'<div class="pull-right select2-result__finding_name"></div>' +
'</div>'
);
var raw = $(result.element).data('raw')
$container.find('.select2-result__name').text(result.name || raw.name || result.text)
$container.find('.select2-result__finding_name').text(result.finding_name_1 || raw.finding_name_1)
return $container
}
此示例使用多个后备。我们总是尝试使用结果中的内容,就像在正常的 ajax 调用中提供的那样,但我们会退回到初始选项的原始数据,如果缺少,则退回到文本字段。