gpt4 book ai didi

jquery - Django-selectable - 在焦点上显示自动完成选项

转载 作者:行者123 更新时间:2023-12-01 05:30:53 24 4
gpt4 key购买 nike

我想在焦点上显示自动完成选项。如果输入的值为空,我想显示所有选项。我想要的行为相当于以下效果:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8/>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</head>
<body>
<input id="text" type="text"></input>
<script>
$(
function() {
$('#text').autocomplete(
{ source: ['abc', 'bcd', 'cde'], minLength: 0 }
).focus(function() { $(this).autocomplete('search'); });
}
);
</script>
</body>
</html>

如何使用 Django-selectable 来做到这一点?

最佳答案

您有机会阅读自动完成文档吗?

特别是关于source选项?

基本上,你需要在你的一端创建一个服务,该服务将返回JSON格式的数据,它可以是字符串列表([“Choice1”,“Choice2”]),带有“label”和“的记录列表” value”键([ { label: "Choice1", value: "value1"}, ... ]),或任何其他数据 - 在这种情况下,您需要另外编写数据解析函数。

对于搜索功能,您的服务应接受“term”查询参数(例如:http://example.com?term=foo)。

要在 Django 中编写此内容,请创建一个 View (基于类或非类),该 View 将响应 GET 请求、查询数据库并返回 JSON 格式的数据(在响应中具有正确的内容/类型 header )

class MyDict(models.Model):
name = models.CharField(max_length=100, db_index=True)

class Meta:
ordering = ['name']

def search_view(request):
term = request.get('term')
search = {}
if term:
search['name__icontain'] = term
# we are limiting answers to not dump whole db over the ajax
# user has a possibility to narrow search
result = [{'label': o.name, 'value': o.name} for o in MyDict.objects.filter(**search)[:50]]
return HttpResponse(json.dumps(result), mimetype='application/json')

关于jquery - Django-selectable - 在焦点上显示自动完成选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37339798/

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