首页 文章

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

提问于
浏览
1

我正在 Laravel 上创建用户 Profiles 页面并使用 select2 组件来过滤大量项目 .

我有一个基于ajax的select2 . 当你在 /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 函数,但没有运气,因为它只创建了 select2 文本元素,当我需要真正的 <option value="1"> something </option> 组件时 .

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

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

1 回答

  • 1

    好吧,您可以尝试使用自己的逻辑来生成类似的选项

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

相关问题