问题
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