如何从 .select2() ajax 调用中获取 <select> 的数据属性以用于 select2?

How to get data attribute of <select> for use in select2 from inside .select2() ajax call?

我需要知道我的 select2 UI 基于什么元素,以便我可以从数据属性中获取数据。也许我在文档中遗漏了它,但我似乎无法弄清楚如何获得它。

以下是我的代码设置的基础知识:

<form>
  <!--SNIP-->
  <select class="select-records" data-index=0>
    <option>Choose some records</option>
  </select>
  <!--SNIP-->
</form>

<script>
  $('.select-records').select2({
    ajax: {
      url: "/ajax/records",
      dataType: 'json',
      delay: 250,
      data: function (params) {
        // Need to get the data-index of the base <select> to process/pass along more info here
        return {
          q: params.term,
          page: params.page
        }
      },
      processResults: function(data, page) {
        return {
          results: data.items
        }
      },
      cache: true
    },
    minimumInputLength: 3
  });
</script>

如您所见,我需要访问定义随 ajax 请求发送的参数的函数内的数据属性(或 ID)。

假设您要为 select 元素添加到 ajax 查询 ...&ui=select1。

  1. 按以下方式定义您的 select:<select data-ajax--id='select1' class="select-records" data-index=0>

  2. 您的 ajax 的数据函数现在应该是:

    函数(参数){ return{ 问:params.term, ui: this.id, 页数:params.page } }