如何使用jQuery ajax实时搜索Django中的模型? [英] How do I jQuery ajax live search for the models in Django?
问题描述
我尝试使用jquery和ajax进行实时搜索,甚至发布了有关此
I tried live search with jquery and ajax, and even posted a question regarding this here, but there seems to have some serious problem somewhere in my view or in the ajax script I wrote. It searches and loads the content correctly.
但是,如果我退格并且搜索表单中没有任何值,它仍会显示我第一次输入的值列表.我认为我的代码中确实存在很大的问题.
But if I backspace and there's no value in the search form, it still shows me a list of value that I entered the first time. I think there's really a big problem in my code.
models.py:
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")
.p的
代码段:
snippet of the .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脚本.
I have already loaded the jquery.min.js script in my template.
推荐答案
我必须在views.py中缩进else语句和return语句.还要在第二个if语句中放入statuss
.然后,它按我预期的那样工作!如果有任何改进,请指导我.谢谢!
I had to indent the else statement and the return statement in the views.py. And also to put statuss
in the second if statement. And then it worked as I expected! Please guide me if there's any improvements to make. Thank you!
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的代码段:
Snippet of 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 %}
这篇关于如何使用jQuery ajax实时搜索Django中的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!