0

所以我正在学习 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 %}

视图.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})
4

1 回答 1

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);
    });
}());
于 2013-09-11T09:04:57.130 回答