我如何jQuery ajax实时搜索Django中的模型?

时间:2013-09-11 14:52:03

标签: jquery ajax django django-models django-views

我尝试使用jquery和ajax进行实时搜索,甚至发布了有关此here的问题,但在我的视图或我编写的ajax脚本中似乎存在某些严重问题。它正确搜索并加载内容。

但如果我退格并且搜索表单中没有值,它仍会显示我第一次输入的值列表。我认为我的代码确实存在很大问题。

models.py:

class Status(models.Model):
    status = models.TextField()
    image = models.ImageField(upload_to=get_upload_file_name, blank=True)
    pub_date = models.DateTimeField(default=datetime.now)
    creator = models.ForeignKey(User, related_name="creator_set")
    likes = models.ManyToManyField(User, through="Like")

.html的摘录:

        <input type="text" id="search" name="search" />
        <ul id="search-results">
        </ul>

views.py:

def search_status(request):

    if request.method == "GET":
        search_text = request.GET['search_text']
        if search_text is not None and search_text != u"":
            search_text = request.GET['search_text']
    else:
        search_text = ''  # I even tried using 0

    statuss = Status.objects.filter(status__contains = search_text)

    return render(request, 'ajax_search.html', {'statuss':statuss})

我已经在我的模板中加载了jquery.min.js脚本。

1 个答案:

答案 0 :(得分:7)

我不得不在views.py中缩进else语句和return语句。并且还将statuss放在第二个if语句中。然后它按照我的预期工作!如果有任何改进,请指导我。谢谢!

views.py:

def search_status(request):

    if request.method == "GET":
        search_text = request.GET['search_text']
        if search_text is not None and search_text != u"":
            search_text = request.GET['search_text']
            statuss = Status.objects.filter(status__contains = search_text)
        else:
            statuss = []

        return render(request, 'ajax_search.html', {'statuss':statuss})

这是ajax脚本:

$(function() {

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

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

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

index.html的片段:

    <input type="text" id="search" name="search" />
    <ul id="search-results">
    </ul>

包含的html:

{% if statuss > 0 %}
    <ul class="statuss">
        {% for status in statuss %}
            <li>
                <p>{{status}}</p>
            </li>
        {% endfor %}    
    </ul>
{% else %}
    <p>No status found.</p>
{% endif %}