选择2 ajax:编辑模式下的预选数据



我正在Laravel上制作用户个人资料页面,并使用select2组件来过滤大量的项目列表。

我有一个基于 ajax 的选择2。当您在页面上时/create这很好,但是当我在第/edit/1页上时,我需要在其中选择值。

$('.search-filter-ajax').select2({
width: '100%',
minimumInputLength: 3,
placeholder: "Search...",
ajax: {
url: '/api/listing/search/',
data: function (term) {
return {
data: term.term
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
search_from: item.name,
model: 'some_model',
id: item.id
}
})
};
},
dataType: 'json',
type: "GET",
delay: 250,
},
});

我尝试使用initSelection函数,但没有运气,因为当我需要真正的<option value="1"> something </option>组件时,它只创建select2文本元素。

initSelection: function (element, callback) {
var id = $(element).data('select-id');
var text = $(element).data('select-text');
callback({ id: id, text: text });
},

如何在页面加载时在 select2 中有一个有效的预选选项,但仍有机会通过 onChange 触发 ajax 调用?

好吧,您可以尝试使用自己的逻辑来生成诸如

$.ajax().then((res)=>{
$('#select').html('');
res.data.forEach((item)={$('#select').append($('option').text(item.text).value(item.value);)})
})

最新更新