Ajax搜索功能在django App中不起作用

时间:2016-02-02 15:00:52

标签: javascript jquery ajax django

我跟随迈克·希伯特(Mike Hibbert)的啧啧之后,试图修改它以满足我的需要,但它不起作用。我想用自己的方式因为我的方式打破了DRY规则,我不得不为我的每个视图编写搜索逻辑我认为它可能是我的js的顺序但是我不认为它是。我可能是错的,因为我对prgramming相当新。我不确定,但我认为问题可能出在我的导航中,我在导航中导航。继承我的代码

views.py

def search_title(request):
if request.method == "POST":
    search_text = request.POST['search_text']
else:
    search_text = ''

posts = Post.objects.filter(
    Q(title__contains=search_text)|
    Q(content__contains=search_text)
)
context = {
    "posts": posts
}
return render(request, "posts/ajax_search.html", context)

我的nav.html

<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="{% url 'posts:list'  %}">HiSPANIC HEiGHTS</a>
    </div>
    <div id="navbar" class="collapse navbar-collapse">


      <form method="POST" action=" "  class="navbar-form navbar-right">
        <div class="input-group">{% csrf_token %}
          <input type="text" name="search" id="search" placeholder="search" value="{{ request.GET.q }}" class="form-control"
          style="width: 350px">

          <ul id="search-results">

          </ul>

        <span class="input-group-btn">
        <button type="submit" class="btn btn-primary"><span style="font-size:1.4em" class="glyphicon glyphicon-search"></span> </button>
        </span>
        </div>
      </form>

      <ul class="nav navbar-nav">
        <li><a href="{% url 'posts:list'  %}">Home</a></li>
        <li><a href="{% url 'posts:sewp'  %}">Sewp</a></li>
        {% if user.is_authenticated %}
        <li><a href="{% url 'admin:index' %}">Admin</a></li>
        <li><a href="{% url 'posts:create' %}">Create</a></li>
        {% endif %}

      </ul>
    </div><!--/.nav-collapse -->
  </div>

base.html文件

{% load staticfiles %}
<html>
<head>
<title> {% block head_title %} try django 1.9 {% endblock head_title %}</title>

<link rel="stylesheet" href='{% static "css/base.css" %}'/>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
      integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
      integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

{% include "includes/nav.html" %}



{% include "includes/messages_display.html" %}

<div class="container">

    {% if title == "posts" %}
    <div class="jumbotron" style="margin-top: 80px">
        {% block jumbotron %}{% endblock jumbotron %}
   </div>
    {% endif %}

    {% block content %}{% endblock content %}
</div>

<!-- Latest compiled and minified JavaScript -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
        crossorigin="anonymous">
</script>

<script src="{% static 'js/ajax.js' %}"></script>
<script src="{% static 'js/jquery.bootstrap-autohidingnavbar.js' %}"></script>

<script>
  $("nav.navbar-fixed-top").autoHidingNavbar();
</script>

ajax.js

 $(function(){

$('#search').keyup(function() {

    $.ajax({
        type: "POST",
        url: "/posts/search/",
        data: {
            'search_text': $('#search').val(),
            'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
        },
        success: searchSuccess,
        dataType: 'html'
    });
  });
  });

  function searchSuccess(data, textStatus, jqXHR)
  {
     $('#search-results').html(data);
  }

我的帖子/ urls.py

urlpatterns = [
url(r'^$',   post_list, name='list'),
url(r'^tag/(?P<slug>[\w-]+)/$', tag_list, name="tag_list"),
url(r'^create/$', post_create, name='create'),
url(r'^sewp$', sewp, name='sewp'),
url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'),
url(r'^(?P<slug>[\w-]+)/edit/$', post_update, name='update'),
url(r'^(?P<id>\d+)/delete/$', post_delete, name='delete'),
url(r'^search/', search_title),
]

我看到网络中没有错误,我已经从GET切换到POST,只是试图调整一些东西以使其工作但没有任何改变。我的jquery来自CDN,但我不认为这是一个问题,但我是一个新手,可能是错的。任何有关这方面的帮助将不胜感激

2 个答案:

答案 0 :(得分:3)

将您的search网址定义移至urlpatterns列表的顶部,这样就不会被post_detail通配符屏蔽:

urlpatterns = [
    url(r'^$',   post_list, name='list'),
    url(r'^search/', search_title),
    url(r'^tag/(?P<slug>[\w-]+)/$', tag_list, name="tag_list"),
    url(r'^create/$', post_create, name='create'),
    url(r'^sewp$', sewp, name='sewp'),
    url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'),
    url(r'^(?P<slug>[\w-]+)/edit/$', post_update, name='update'),
    url(r'^(?P<id>\d+)/delete/$', post_delete, name='delete'),
]

来自docs

  

Django按顺序遍历每个URL模式,并在第一个匹配请求的URL的位置停止。

您的post_detail正则表达式肯定与search/匹配。

答案 1 :(得分:0)

我认为您可能需要在搜索网址字符串末尾添加$。

url(r'^search/$', search_title),

这让django知道它是字符串的结尾。除非你已经确认你实际上已经能够发送到search_title视图。