我正在尝试在用户界面中实现自动完成搜索栏。
HTML:
<div>
<input type="text" name="apexClass" id="autocomplete"/>
</div>
我用过devbridge js:
$('#autocomplete').autocomplete({
type:'POST',
serviceUrl: 'http://localhost:8989/getSuggestion',
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value);
}
});
然后在服务器端,我有此Rest服务:
@RequestMapping(value = "/getSuggestion", method = RequestMethod.POST)
public String getSuggestion(String query) throws IOException {
Gson gson = new GsonBuilder().create();
List<String> strings = stringListHashMap.get("suggestions");
Iterator itr = strings.iterator();
while (itr.hasNext())
{
String x = (String)itr.next();
if (!x.contains(query))
itr.remove();
}
stringListHashMap.put("suggestions", strings);
return gson.toJson(stringListHashMap);
}
现在的问题是,第一次加载页面时,我可以从搜索栏中获取查询,并从列表中删除elemnet,然后显示它们,但是当我删除查询时,我无法将列表中的值保留为我已经使用了迭代器并将其删除。
在devbridge文档中,其书面内容是,当我们使用serviceURL时,服务器端负责过滤结果。但是我现在陷入困境。
我该如何纠正呢?
最佳答案
好的,我得到了答案,它是从服务器端发出的。我将代码更改如下:
将父数据保持独立,并创建要传递给UI的新数据集。这样,原始数据集将始终存在。
@RequestMapping(value = "/getSuggestion", method = RequestMethod.POST)
public String getSuggestion(String query) throws IOException {
Gson gson = new GsonBuilder().create();
List<String> strings = stringListHashMap.get("suggestions");
Map<String, List<String>> newMapReturn = new HashMap<>();
List<String> newListToBeAdded = new ArrayList<>();
Iterator itr = strings.iterator();
while (itr.hasNext())
{
String x = (String)itr.next();
if (x.toLowerCase().contains(query.toLowerCase()))
newListToBeAdded.add(x);
}
newMapReturn.put("suggestions", newListToBeAdded);
return gson.toJson(newMapReturn);
}