jquery ajax加载结果列表,甚至没有什么可以查询 [英] jquery ajax loads list of results even there's nothing to query
本文介绍了jquery ajax加载结果列表,甚至没有什么可以查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我正在从jQuery和ajax的教程中学习,直到现在我有一个搜索表单来搜索和返回搜索结果。它工作正常但是当我从表单中删除单词或退格单词时,它将加载列表中的所有状态。
So I am learning from a tutorial for jquery and ajax and till now I have a search form for searching and returning the search results. And it works fine. But when I delete the words from the form or backspace the words, it loads all the status in the list. What do I do to return only when there is some word and to return nothing if there's no word in the form.
status.html的片段:
snippet of 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:
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})
推荐答案
$('#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'
});
});
BTW,您应该在键盘上调整您的请求,以避免多次调用,如果用户输入的速度太快: / p>
BTW, you should throttle your request on keyup to avoid multiple call if user is typing too fast:
(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);
});
}());
这篇关于jquery ajax加载结果列表,甚至没有什么可以查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文