Select2 - Dropdown is not showing while API is working

℡╲_俬逩灬. 提交于 2019-12-25 08:49:23

问题


I am using the Select2 for my autocompletion and I am loading the list from remote.

Have a look at the code below:

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>

The problem: While the network calls are being made to the URL with the params and the results are coming back, it is not showing up in my dropdown.

Actual API response (which I have seen from the browser Network logs:

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

This is what the front-end looks like:

So the API responses are working okay. What I am doing wrong here?

Thanks in advance


回答1:


This was fixed, thanks to something JohnS pointed out on this post.

The problem was that processResults is supposed to return an id and text variables. You will just have to map them, as per my final solution below:

$(".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: This also includes some cleaning up of the code but the problem was with the missing variables.



来源:https://stackoverflow.com/questions/42049399/select2-dropdown-is-not-showing-while-api-is-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!