【问题标题】:Dynamic select2 options using api使用 api 的动态 select2 选项
【发布时间】:2018-06-30 09:24:44
【问题描述】:

我会尽量解释我的问题。我正在尝试使用select2 插件创建一种让用户编写一些字母的方法,并在每个字母上按下对 API 的调用,该 API 会给出该 API 给出的前 20 个结果。

所以我有我的 HTML 选择:

<select name="filtre_products[]" class="form-control products-select2" multiple> 

</select>

然后是我的 JS(已注释):

$(".products-select2").select2({ 
    width: '100%', 
    closeOnSelect: false,
    placeholder: '',
    minimumInputLength: 3,
    query: function (query) {
        var data = {results: []}, i, j, s;
        if(query.term != null) {
            var ajax_r = [];
            $.ajax({
                url: 'ajax_products_recherche.php?limite=10&real_json=1&recherche='+query.term,
                success: function(data_a){
                    //Getting the data
                    data_a = JSON.parse(data_a);

                    //Looping through the each data and putting them inside a table
                    data_a.forEach( (e) => {
                        ajax_r.push(e);
                    });

                    //Filtering the data to get from it the id and the text to be used
                    ajax_r.forEach( (e) => {
                        var tmp = e.split('-');
                        var id = tmp[0];
                        var name = tmp[2];

                        data.results.push({value: id, text: name});
                    });

                    query.callback(data);
                }
            });
        }
    },
    //Sending the results to the function to modify the options as I please
    templateResult: formatResult
});

这是我使用的formatResult 函数:

function formatResult(d) {
    if(d.loading) {
        return d.text;
    } 

    // Creating an option of each id and text
    $d = $('<option/>').attr({ 'value': d.value }).text(d.text);

    return $d;
}

我的问题是 select2 应该在初始化时动态创建选项,因此实际上从选项中创建 &lt;li&gt; 并动态添加它们的 ID 等。但是在我创建它的方式中,它将选项放在&lt;li&gt; 标记内,这不是我想要的,我希望它像他在没有查询调用的情况下那样将其视为动态选项。

为你们提供一些文档资源,它显示了我正在尝试做的一部分,但该示例显示了如何显示我们编写的结果,我希望它在每次点击时从 api 中显示,以及课程添加了多项选择: http://select2.github.io/select2/#data

【问题讨论】:

    标签: javascript jquery jquery-select2


    【解决方案1】:

    我已阅读文档并发现ajax support 似乎符合您的需求。

    在您的 select2 选项对象中,添加一个 ajax 对象。在这个ajax 对象内:

    • 为 ajax 调用定义常规参数(url、数据类型、延迟等)
    • 在 data 属性中,定义返回应添加到 queryString 中的查询参数的函数
    • 在processResults 属性中,定义一个函数来处理ajax 调用返回的数据并返回一个包含results 数组的对象(就像您已经在构建的数据对象一样)。

    然后,您可以重用您的模板函数。

    这是一个带有随机 API 的工作 sn-p。请注意,查询的术语不会影响返回的数据。

    $(document).ready(function () {
    
      $(".products-select2").select2({
        width: '100%',
        closeOnSelect: false,
        placeholder: '',
        minimumInputLength: 3,
        ajax: {
          url: "https://jsonplaceholder.typicode.com/users",
          dataType: 'json',
          delay: 250,
          data: function (query) {
            // add any default query here
            return query;
          },
          processResults: function (data) {
            // Tranforms the top-level key of the response object from 'items' to 'results'
            var results = [];
            data.forEach(e => {
              results.push({ id: e.id, text: e.name });
            });
    
            return {
              results: results
            };
          },
        },
        templateResult: formatResult
      });
      
      function formatResult(d) {
        if(d.loading) {
            return d.text;
        } 
    
        // Creating an option of each id and text
        $d = $('<option/>').attr({ 'value': d.value }).text(d.text);
    
        return $d;
    }
    
    });
    <html>
      <head>
          <script src="https://code.jquery.com/jquery-3.3.1.min.js">
          </script>
    
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.full.js"></script>
      </head>
    <body>
    
      <select name="filtre_products[]" class="form-control products-select2" multiple> 
      </select>
    
    </body>
    </html>

    【讨论】:

      【解决方案2】:

      对于您的 ajax 成功调用,请执行此操作或类似操作。我认为你不需要这么大的代码。下面的代码 sn-p 来自我的工作脚本。

      success: function (data) {
      
                      var dbSelect = $('#ddlItems'); // id for  Dropdown list
                      dbSelect.empty();
                      result = JSON.parse(data);
                      // Parse result object and create your array collection in ajax_r object
                      for (var i = 0; i < ajax_r.length; i++) {
                          dbSelect.append($('<option/>', {
                              value: ajax_r.item[i].Value,
                              text: ajax_r.item[i].Text
                          }));
                      }
                  }
      

      【讨论】:

        猜你喜欢
        • 2015-10-10
        • 1970-01-01
        • 2018-03-02
        • 2015-08-16
        • 2018-06-12
        • 2021-09-03
        • 1970-01-01
        • 2017-12-17
        • 2014-09-23
        相关资源
        最近更新 更多