简体   繁体   中英

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. 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). After fetching those, I want to create options out of those and add them to select2 so they user can select one of them.

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 . When I search for anything, the options are generated correctly, however, the append seems to fail as no options are displayed at all. It looks like this:

搜索后选择2

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 ).

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.

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. Further down there were some examples and one of them shows that those objects contain 2 keys - id and 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). 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.

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.

This is another fiddle with analogous behaviour but done according to those findings from the documentation: https://jsfiddle.net/mkilmanas/3s0kupaw/5/

processResults Is not used to append options to the select2. It is used to transform the response from the API. It should return a valid array of objects to feed 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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM