[英]get value from php/mysql autocompletion
我有一些腳本可以從mysql數據庫在表城市上搜索城市。 一切正常,但是當我單擊結果時想要顯示結果時,請在輸入搜索中顯示該結果。 有幫助我的主意嗎?
JQUERY
<script type='text/javascript'>
$(document).ready(function() {
$("#search_results").slideUp();
$("#button_find").click(function(event) {
event.preventDefault();
search_ajax_way();
});
$("#search_query").keyup(function(event) {
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way() {
$("#search_results").show();
var search_this = $("#search_query").val();
$.post("mod/search.php", {
searchit: search_this
}, function(data) {
$("#display_result").html(data);
})
}
</script>
PHP
$term = strip_tags(substr($_POST['searchit'], 0, 100));
$term = utf8_decode($term);
$term = mysql_escape_string($term); // Attack Prevention
$query = mysql_query("select distinct city from city where (city like '{$term}%') order by city limit 10 ");
if (mysql_num_rows($query)) {
while ($row = mysql_fetch_assoc($query)) {
echo ''.utf8_encode($row['city']).
'<BR>';
}
} else {
echo 'No result';
}
HTML
<input type="text" style="width:60%;margin-right:10px;" name="search_query" id="search_query" value="" autocomplete="off">
<div id="display_result"></div>
您將需要在一個元素中輸出各個城市,而不僅僅是用<br>
隔開,然后需要監聽onclick
delegated
事件。
例如
PHP:
echo "<ul>";
if (mysql_num_rows($query)) {
while ($row = mysql_fetch_assoc($query)) {
echo '<li class="search-city">'.utf8_encode($row['city']).
'</li>';
}
} else {
echo '<li>No result</li>';
}
echo '</ul>';
然后,在javascript中,您需要偵聽委托事件,因為從第一次加載javascript時頁面加載開始就沒有元素。 https://learn.jquery.com/events/event-delegation/
因此,您需要執行以下操作:
使用Javascript:
$(document).on("click", "li.search-city", function(){
// Now do whatever you want with the clicked value
console.log($(this).val());
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.