当API工作时,Select2 – Dropdown未显示
我正在使用Select2进行自动完成,我正在从远程加载列表。
看看下面的代码:
HTML:
jQuery的:
$(".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, } }) }; } } });
问题:当使用params对URL进行网络调用并且结果返回时,它不会显示在我的下拉列表中。
实际API响应(我从浏览器网络日志中看到:
[{"name":"bottomline-technologies"}]
这就是前端的样子:
所以API响应工作正常。 我在这做错了什么?
提前致谢
由于JohnS在这篇文章中指出了一些内容,这一问题已得到解决。
问题是processResults应该返回id和text变量。 根据我的最终解决方案,你只需要映射它们:
$(".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:这还包括一些清理代码,但问题是缺少变量。