【发布时间】:2016-04-19 21:46:35
【问题描述】:
我正在使用 Twitter typeahead 来使我的搜索栏正常工作,但遇到了一些问题。
搜索栏的用途:
搜索栏将用于搜索注册到该站点的用户的用户名。
方法:
在home.php的head中:
<script src="typeahead.min.js"></script>
header.php(包含在home.php中):
<input type="text" class="form-control" placeholder="Search user" name="typeahead">
<script>
$(document).ready(function(){
$('input.typeahead').typeahead({
name: 'typeahead',
remote:'search.php?key=%QUERY',
limit : 10
});
});
</script>
search.php:
<?php
include("connect.php");
$key=$_GET['key'];
$array = array();
$query = mysqli_query("SELECT * FROM users WHERE username LIKE '%{$key}%'");
while($row=mysqli_fetch_assoc($query)){
$array[] = $row['username'];
}
echo json_encode($array);
?>
目前的结果:
如果使用上面的代码,在home.php我尝试搜索用户Alice,他是一个真正的用户(我没有点击搜索,我只是在搜索栏中输入她的名字. 我希望,如果 Alice 是一个真实的用户,她的名字会出现在下拉菜单中)。但如果我搜索她,URL 会发生变化。
总结: 如果我输入 Alice(不要按搜索),什么也不会发生。我希望出现一个下拉菜单,因为 Alice 是一个真实的用户名。
如果我输入 Alice 并单击搜索按钮,则 URL 将更改为:
http://localhost/home.php?typeahead=Alice
编辑:
我在header.php尝试的另一种方法:
<input type="text" class="form-control" placeholder="Search user" name="typeahead">
<?php
// getting all usernames from db
$statement = mysqli_prepare ($connect, "SELECT * FROM users WHERE account_type ='user'");
mysqli_stmt_execute($statement);
$usernames = array();
$result = mysqli_stmt_get_result($statement);
while($get_data = mysqli_fetch_assoc ($result)){
$usernames[] = $get_data['username'];
}
mysqli_stmt_close($statement);
?>
<script>
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
var username = <?php echo json_encode($usernames); ?>;
$('#the-basics .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'usernames',
source: substringMatcher(username)
});
</script>
从Github采用了以下方法。
使用这种方法,我仍然没有得到显示任何匹配名称的下拉列表。
【问题讨论】:
标签: php search typeahead.js bootstrap-typeahead twitter-typeahead