【问题标题】:Django-selectable - show autocomplete options on focusDjango-selectable - 在焦点上显示自动完成选项
【发布时间】:2016-09-17 07:29:38
【问题描述】:

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

<!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 做到这一点?

【问题讨论】:

    标签: jquery python django jquery-ui


    【解决方案1】:

    您是否有机会阅读有关自动完成功能的文档?

    尤其是source 选项?

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

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

    要在 Django 中编写此内容,请创建一个视图(基于或不基于类),它将响应 GET 请求、查询数据库并返回格式为 JSON 的数据(在响应中带有适当的内容/类型标头)

    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')
    

    【讨论】:

    • 这不是问题的答案 - 问题是如何在焦点上和键入后显示自动完成选项,以便用户不必键入即可获得一些基本选项。
    猜你喜欢
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    相关资源
    最近更新 更多