[英]Select2 - Fetch data from backend and add options to selectbox
I'm currently trying to get select2 to work, however, I'm struggling a little bit right now.我目前正在尝试让 select2 工作,但是,我现在有点挣扎。 What I want to achive, is fairly simple: I fetch a JSON from a webserver which consists out of key/value pairs (one ID to one string).我想要实现的目标非常简单:我从由键/值对(一个 ID 到一个字符串)组成的网络服务器获取 JSON。 After fetching those, I want to create options out of those and add them to select2 so they user can select one of them.获取这些后,我想从中创建选项并将它们添加到 select2 以便他们用户可以使用 select 其中之一。
I kept as close to the code in the documentation as humanly possible:我尽可能接近文档中的代码:
$('#catSearchBox').select2({
width: '500px',
ajax: {
url: "url/to/data",
dataType: 'json',
delay: 250,
cache: false,
data: function (params) {
return {
searchKey: params.term
};
},
processResults: function (data, params) {
$.each(data, function(catName, catId) {
var newOption = new Option(catId, catName, false, false);
$('#catSearchBox').append(newOption).trigger('change');
});
}
},
placeholder: 'Suche nach Kategorie ...',
minimumInputLength: 3
});
Now, everything here works up until the append
.现在,这里的一切都可以正常工作,直到append
。 When I search for anything, the options are generated correctly, however, the append seems to fail as no options are displayed at all.当我搜索任何内容时,选项都会正确生成,但是 append 似乎失败了,因为根本没有显示任何选项。 It looks like this:它看起来像这样:
However, it's not because of an empty or invalid response, because the options are definitely created:但是,这不是因为响应为空或无效,因为肯定会创建选项:
I'm kinda at a loss here, I don't see why my code is not working, especially since I kept as close as possible to the code in the documentation ( https://select2.org/data-sources/ajax andhttps://select2.org/programmatic-control/add-select-clear-items ).我在这里有点不知所措,我不明白为什么我的代码不起作用,特别是因为我尽可能接近文档中的代码( https://select2.org/data-sources/ajax和https://select2.org/programmatic-control/add-select-clear-items )。
Does anyone have any idea on how to solve this problem?有谁知道如何解决这个问题? If you need any additional information I might have missed out, please let me know.如果您需要我可能错过的任何其他信息,请告诉我。
I believe the main problem is in your processResults
function and Select2's expectations of it.我相信主要问题在于您的processResults
function 和 Select2 对它的期望。
From what I was able to partly read and partly deduce from the documentation at https://select2.org/data-sources/ajax#transforming-response-data is that processResults
is supposed to return an object containing a key results
and those results should be an array of objects.从我能够从https://select2.org/data-sources/ajax#transforming-response-data的文档中部分阅读和部分推断出来, processResults
应该返回一个包含关键results
和这些结果的 object应该是一个对象数组。 Further down there were some examples and one of them shows that those objects contain 2 keys - id
and text
.再往下有一些例子, 其中一个显示这些对象包含 2 个键 - id
和text
。
Moreover, the info box at the top of the docs it says that select2 will create <option>
only for element that was chosen (it's done for performance reasons).此外,文档顶部的信息框说 select2 只会为选择的元素创建<option>
(出于性能原因这样做)。 This implies that you are not supposed to create the <option>
elements yourself, but just return the data in the expected format and select2 will take care of the rest.这意味着您不应该自己创建<option>
元素,而只需以预期格式返回数据,select2 将处理 rest。
This is a fiddle based on your code: https://jsfiddle.net/mkilmanas/jkx2mwv5/1/ and it doesn't work, it throws an error of trying to access results
of undefined.这是基于您的代码的小提琴: https://jsfiddle.net/mkilmanas/jkx2mwv5/1/它不起作用,它会引发尝试访问未定义results
的错误。
This is another fiddle with analogous behaviour but done according to those findings from the documentation: https://jsfiddle.net/mkilmanas/3s0kupaw/5/这是另一个类似行为的小提琴,但根据文档中的这些发现完成: https://jsfiddle.net/mkilmanas/3s0kupaw/5/
processResults Is not used to append options to the select2. processResults 不习惯 append 选项给select2。 It is used to transform the response from the API.它用于转换来自 API 的响应。 It should return a valid array of objects to feed select2.它应该返回一个有效的对象数组来提供 select2。
Something like:就像是:
var newData = [];
$.each(data, function(catName, catId) {
newData.push({ id: catId, text: catName });
});
return { results: newData };
I'm not sure if this is the solution but there are 2 things in your code that I don't like so much.我不确定这是否是解决方案,但您的代码中有两件事我不太喜欢。
Try this:尝试这个:
processResults: function (data, params) {
// First, remove all previous elements
$('#catSearchBox').html('');
$.each(data, function(catName, catId) {
var newOption = new Option(catId, catName, false, false);
$('#catSearchBox').append(newOption);
});
// Second, fire change when all elements are appended
$('#catSearchBox').trigger('change');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.