6

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

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

模型.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>

视图.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 脚本。

4

1 回答 1

9

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

视图.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 %}
于 2013-09-11T17:12:27.920 回答