I have search engine that works except for this keyup function.As user types an input it should display the words(ex if I type a, then search bar should show the results that starts with a)but this function isn't working. I have to type all the words then enter to get the result. I went back to jquery tutorial for this but I still don't understand. Thank you in advance.
This is my js code.
$(function(){
$('#search').keyup(function() {
$.ajax({
type: "POST",
url: "/search/",
data: {
'search_text' : $('#search').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR)
{
$('#search-results').html(data);
}
Then to call this code I have
<script type="text/javascript" src="{% static 'js/ajax.js' %}"></script>
And I have more in my index html
<h3>Search</h3>
{% csrf_token %}
<input type="text" id="search" name="search" />
<ul id="search-results">
</ul>
With this code, nothing shows up. but inside my search.html search engine works and here's the code
<form method="get" action=".">
<table>
{{ form.as_table }}
<tr>
<td> </td>
<td>
<input type="submit" value="search">
</td>
</tr>
</table>
{% if query %}
<h3>result</h3>
{% for result in page.object_list %}
<p>
<a href="{{ result.object.get_absolute_url }}">{{ result.object.name }}</a>
</p>
{% empty %}
<p>no result</p>
{% endfor %}
{% if page.has_previous or page.has_next %}
<div>
{% if page.has_previous %}<a href="/category/{{post.category}}">{% endif %}« Previous{% if page.has_previous %}</a>{% endif %}
|
{% if page.has_next %}<a href="/category/{{post.category}}">{% endif %}Next »{% if page.has_next %}</a>{% endif %}
</div>
{% endif %}
{% else %}
{# Show some example queries to run, maybe query syntax, something else? #}
{% endif %}
</form>
please ignore any {} code up there as they are django. my question is how do I use the jquery function to work in either index or search.html? my goal was to use search engine in index page but it just won't work so I want to use keyup function in my search.html///thank you in advance
does your binding method ever get called in a onload
function or anything? If not, I would suggest doing so. If your are not comfortable to set the binding on the page load, you can add the handler to the html-tag directly:
function handle_keyup() {
$.ajax({
type: "POST",
url: "/search/",
data: {
'search_text' : $('#search').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
}
and in your template:
<input type="text" id="search" name="search" onkeyup="handle_keyup()"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.