gpt4 book ai didi

javascript - 坚持根据来自restFul API的数据实现自动完成

转载 作者:太空宇宙 更新时间:2023-11-04 10:46:14 25 4
gpt4 key购买 nike

我正在尝试在用户界面中实现自动完成搜索栏。

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);
}

关于javascript - 坚持根据来自restFul API的数据实现自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48386334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com