使用 Select2 附加 AJAX 获取的值

Attach AJAX fetched value with Select2

我正在尝试将 AJAX 获取的值附加到 Select2。我的 JavaScript 代码如下。

(function($) {  
  $(document).ready(function() {
    $(".volunteer").on("click", function (event) {
      let element_id = event.target.id;
      // Check if select is already loaded
      if (!$(this).has("select").length) {
        var cellEle = $(this);

        // Populate select element
        cellEle.html(`<select class="js-example-basic-multiple" multiple="multiple"></select>`);

        // Initialise select2
        let selectEle = cellEle.children("select").select2({
          ajax: {
            url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
            dataType: 'json',
            data: function (params) {
              return { 
                q: element_id,
                        action: 'get_data'
                    };
            },
            type: "post",
            processResults: function(data) {              
              var options = [];
              if ( data ) {
                $.each( data, function( index, text ) {
                  options.push( { text: text  } );
                });
              }
              return {
                results: options
              };
            }
          }
        });
      }
    });
  });
})(jQuery)

我得到如下输出。

如果我点击任何值,它不会设置到 select 框。值不起作用。

Select2 要求每个选项都有一个 id 属性 和一个 text 属性。在上面的代码中,processResults 方法返回一个对象数组,其中仅包含 text 属性,不包含 id。将对象添加到 processResults 中的数组时,应包含 id

options.push({ id: id, text: text });

有关此格式的详细信息,请参见 https://select2.org/data-sources/formats。根据此页面:

Blank ids or an id with a value of 0 are not permitted.

您可以使用 text 作为 id 值(如果它是唯一的),或者使用 index + 1(+ 1 以避免值为 0)。在下面的示例代码中,使用了 text

processResults: function(data) {
  var options = [];
  if (data) {
    $.each(data, function (index, text) {
      options.push({ id: text, text: text });
    });
  }
  return {
    results: options
  };
}