从php/mysql获取值自动完成

问题描述:

我有一些脚本从mysql数据库中搜索城市表城。 一切正常,但当结果显示时,我想单击结果时,将其显示在我的输入搜索中。 帮助我的想法?从php/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> 
+0

您可以用'typeahead' –

您将需要输出中的一个元素的各个城市,而不是仅仅通过<br>的分离,然后需要听delegated事件为onclick

例如

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()); 
});