【发布时间】:2020-11-16 07:22:22
【问题描述】:
我们已经找到了几个为 Select2 预先填充选定选项的示例,但是我们都找不到处理格式化列表和选择选项的示例。我们在https://jsfiddle.net/gpsx62de/26/ 有一个 JS fiddle 来说明这个问题。在那个小提琴中,您可以在选择搜索中键入和 L 或其他内容,然后返回数据,格式化列表,如果您选择某些内容,则格式化选择。
但是,如果您单击该 JS Fiddle 中的按钮,该按钮旨在模拟每个 https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2 的预填充数据,则会返回数据(您可以取消注释 console.log 以查看它),但格式化的选择显示未定义预期值。有谁知道让预填充数据的格式化值正确显示的方法?
// 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); //**** DOES IT MATTER WHAT IS PASSED HERE BECAUSE WE ARE NOT DISPLAY THE OPTION TEXT?? ***
studentSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
studentSelect.trigger({
type: 'select2:select',
params: {
data: data //**** THIS DOES NOT SEEM TO SUPPORT FORMATTED SELECTIONS, SO HOW CAN THIS BE DONE? ***
}
});
});
【问题讨论】:
-
您好,我检查了小提琴,您确定您使用的 URL 正确吗?看来来源真的不存在。
-
它为我返回数据。你看到控制台日志输出了吗?
标签: javascript jquery ajax jquery-select2