jquery ajax加载结果列表,即使没有什么可查询的

时间:2013-09-11 09:02:09

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

所以我正在学习jquery和ajax的教程,到现在为止我有一个搜索表单用于搜索和返回搜索结果。它工作正常。但是当我从表单中删除单词或退格单词时,它会加载列表中的所有状态。如果表单中没有任何单词,我该怎么做才能返回,如果表单中没有单词则不返回任何内容。

status.html的摘录:

{% block add_account %}
<input type="text" id="search" name="search" />

<ul id="search-results">

</ul>

{% endblock %}

ajax.js:

$(function() {

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

        $.ajax({
            type: "POST",
            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)
}

ajax.html:

{% if statuss.count > 0 %}

{% for status in statuss %}
    <li><a href="/status/get/{{status.id}}/">{{status.status}}</a></li>
{% endfor %}

{% else %}

<p>None to show</p>

{% endif %}

views.py

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

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

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

1 个答案:

答案 0 :(得分:1)

$('#search').keyup(function () {
    if (!$.trim(this.value).length) return; //<< returns from here if nothing to search
    $.ajax({
        type: "POST",
        url: "/status/search_status/",
        data: {
            'search_text': $('#search').val(),
                'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
        },
        success: searchSuccess,
        dataType: 'html'
    });
});
顺便说一下,如果用户键入太快,你应该在keyup上限制你的请求,以避免多次调用:

(function () {
    var throttleTimer;
    $('#search').keyup(function () {
        clearTimeout(throttleTimer);
        throttleTimer = setTimeout(function () {
            if (!$.trim(this.value).length) return;
            $.ajax({
                type: "POST",
                url: "/status/search_status/",
                data: {
                    'search_text': $('#search').val(),
                        'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
                },
                success: searchSuccess,
                dataType: 'html'
            });
        }, 100);
    });
}());