首页 > 解决方案 > 使用 api 的动态 select2 选项

问题描述

我会尽量解释我的问题。我正在尝试使用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应该在初始化时动态创建选项,因此实际上是<li>从选项中创建出来并动态添加到它们的 id 等。但在我创建它的方式中,它把选项放在<li>标签中,这不是我想要的,我希望它把它当作动态选项,就像他在没有查询调用的情况下所做的那样。

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

标签: javascriptjqueryjquery-select2

解决方案


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

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
                    }));
                }
            }

推荐阅读