I could finally get my ajax search work, but I couldn't hide the results when I clear the input text box. Also, I couldn't select the search result so that it should retain in the input text box
以下是Ajax代码: 的 Ajax.js
$(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);
}
这是html模板 的 Template.html
<input type="text" id="search" name="search" class="search" value="Enter Loc" size="35" maxlength="300" style="margin-left:10px;color:#d5caca" onclick="document.getElementById('search').value = ''" />
<a class="lr" style="text-decoration:none" href="#">Search</a>
<ul id="search-results" style="color:#ffffff;margin-left:35%">
</ul>
先谢谢你的帮助!**
答案 0 :(得分:1)
如果值为空,则清除结果面板
$(function () {
$('#search').keyup(function () {
//clear result panel if the value is blank
if (!this.value.trim()) {
$('#search-results').html('');
return;
}
$.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);
}