【问题标题】:Select2 - Dropdown is not showing while API is workingSelect2 - API 工作时不显示下拉菜单
【发布时间】:2023-03-20 10:35:02
【问题描述】:

我正在使用 Select2 进行自动完成,并且正在从远程加载列表。

看看下面的代码:

HTML:

<div>
    <select class="tagsSearch" style="width: 100%">
        <option value="2" selected="selected"></option>
    </select>
</div>

jQuery:

<script type="text/javascript">
$(".tagsSearch").select2({
placeholder: 'Search for tags',
tags: true,
multiple: true,
tokenSeparators: [',', ' '],
minimumInputLength: 2,
minimumResultsForSearch: 1,
ajax: {
    url: function (params) {
        return '/api/searchTags?text=' + params.term;
    },
    dataType: "json",
    type: "GET",
    processResults: function (data) {
        return {
            results: $.map(data, function (name) {
                return {
                    name: name,
                }
            })
        };
    }
}
});
</script>

问题:当使用参数对 URL 进行网络调用并且结果返回时,它没有显示在我的下拉列表中。

实际 API 响应(我从浏览器网络日志中看到的:

[{"name":"bottomline-technologies"}]

这是前端的样子:

所以 API 响应工作正常。我在这里做错了什么?

提前致谢

【问题讨论】:

    标签: jquery select2


    【解决方案1】:

    感谢 JohnS 在 this 帖子中指出的内容,此问题已得到解决。

    问题在于 processResults 应该返回一个 idtext 变量。根据我下面的最终解决方案,您只需映射它们:

    $(".tagsSearch").select2({
    placeholder: 'Search for tags',
    delay: 250,
    tags: true,
    multiple: true,
    tokenSeparators: [',', ' '],
    minimumInputLength: 2,
    minimumResultsForSearch: 1,
    ajax: {
        url: function (params) {
            return '/api/searchTags';
        },
        dataType: "json",
        type: "GET",
        data: function (params) {
            return {
                text: params.term 
            };
        },
        processResults: function(data){
            return{
                results: $.map(data, function(obj){
                return {
                    id: obj.name, text: obj.name // <- this is what was done to fix the issue
                };
              })
            };
        }}
    });
    

    PS:这还包括对代码的一些清理,但问题在于缺少变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      • 2021-10-14
      • 2017-01-30
      • 1970-01-01
      • 2022-01-01
      相关资源
      最近更新 更多