用AJAX数据填充Select2

Dev*_*per 5 jquery jquery-select2

我正在使用Select2 4.0.0-rc.2。

选项”页面指出以下内容:initSelection

过去,Select2要求initSelection在使用自定义数据源时就定义一个选项,从而可以确定组件的初始选择。它已由数据适配器current上的方法代替。

我仅找到了使用的旧版本Select2的示例initSelection(请参阅使用Ajax在Select2上设置加载时的初始值

如何使用数据适配器加载默认数据?

这是我的初始代码(是树枝)

 $("#{{ id }}").select2({
            ajax: {
                    url: "{{ path(attr.path) }}",
                    dataType: 'json',
                    {% if attr.placeholder is defined %}
                    placeholder: '{{ attr.placeholder }}',
                    {% endif %}
                    delay: 250,
                    data: function (term) {
                        return term;
                    },
                    processResults: function (data) {
                        return {results: data};
                    }

                },
            templateResult: function(data){
                return '<img width="30" src="'+data.image+'">'+data.text;
            },
            templateSelection: function(data){
                return '<img width="30" src="'+data.image+'">'+data.text;
            },

            cache: true,
            escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
            minimumInputLength: 2
        });
Run Code Online (Sandbox Code Playgroud)

如果可能的话,我希望安装程序始终显示可见选项,并设置其他ajax,

小智 5

<select id="posow"></select>
Run Code Online (Sandbox Code Playgroud)

对于上面的选择我喜欢这样:

$(function () {
            $.getJSON( "/f3/tokenize/PO_SoW", function(respond) {
                $('#posow').select2({
                    multiple: true,
                    data: respond
                });
             });
});
Run Code Online (Sandbox Code Playgroud)

服务器的响应是这样的:

[{id: 'nms', text: 'FATP'},
{id: 'nms', text: 'ATF Plan'},
{id: 'nms', text: 'Endorse Plan'},
{id: 'nms', text: 'Endorse Date'}
]
Run Code Online (Sandbox Code Playgroud)


Luí*_*ruz 3

您对他们的文档有详细的解释。如果您只需要加载数据一次,则可以使用以下代码(已从其文档页面中删除)来执行此操作:

var $element = $('select').select2(); // the select element you are working with

var $request = $.ajax({
  url: '/my/remote/source' // wherever your data is actually coming from
});

$request.then(function (data) {
  // This assumes that the data comes back as an array of data objects
  // The idea is that you are using the same callback as the old `initSelection`

  for (var d = 0; d < data.length; d++) {
    var item = data[d];

    // Create the DOM option that is pre-selected by default
    var option = new Option(data.text, data.id, true, true);

    // Append it to the select
    $element.append(option);
  }

  // Update the selected options that are displayed
  $element.trigger('change');
});
Run Code Online (Sandbox Code Playgroud)