繁体   English   中英

在Django Webapp中使用jQuery和AJAX自动完成搜索

[英]Autocomplete search with jquery and AJAX in django webapp

我正在尝试通过遵循本教程来实现自动完成搜索

https://medium.com/@ninajlu/django-ajax-jquery-search-autocomplete-d4b4bf6494dd

而且我无法实现它,并且我认为它与我的URL或将脚本放入.html文件的方式有关。

我的搜索栏在索引视图中

的index.html

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>


</head>
<body>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'KPI/style.css' %}">

<script>
        $(document).ready(function(){
            $("#txtSearch").autocomplete({
                source: "/login/index",
                minLength: 2,
                open: function(){
                    setTimeout(function () {
                        $('.ui-autocomplete').css('z-index', 99);
                    }, 0);
                }
              });

        });

</script>

<form id="search" method="POST" action="{% url 'kpi:search' %}">
 {% csrf_token %}
 <input type="text" class="form-control" id="txtSearch" name="txtSearch">
 <button type="submit" class="btn btn-default btn-submit">Submit</button>
 </form>
</body>
</html>

urls.py

app_name = 'kpi'
urlpatterns = [
 path('login/', views.LoginView.as_view(), name='login'),
 path('login/index/', views.IndexView.as_view()),
]

现在在本教程中,它说要放置此路径url(r'^ajax_calls/search/', autocompleteModel),但似乎该路径不一定是这种方式,因此我将路径更改为login/index/ ,称为类视图IndexView ,它像这样保存autocompleteModel

views.py

class IndexView(LoginRequiredMixin,TemplateView):
    template_name = 'KPI/index.html'

    def autocompleteModel(self,request):
        if request.is_ajax():
            q = request.GET.get('term', '').capitalize()
            search_qs = Epic.objects.filter(name__icontains=q)
            results = []
            print(q)
            for r in search_qs:
                results.append(r.name)
            data = json.dumps(results)
        else:
            data = 'fail'
        mimetype = 'application/json'
        return JsonResponse(data, mimetype)

Epic是我正在使用值name搜索的模型。

我上面的代码无法执行任何操作,我希望有人可以看到它的缺陷。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM