【发布时间】:2016-05-31 20:41:04
【问题描述】:
从下面的 jQuery 代码中我已经初始化了 typeahead 插件
var users=new Bloodhound({
datumTokenizer:Bloodhound.tokenizers.obj.whitespace('username'),
queryTokenizer:Bloodhound.tokenizers.whitespace,
remote: {
url: 'users.php?query=%QUERY',
wildcard: '%QUERY'
}
});
users.initialize();
$("#SearchCustomer").typeahead({
hint: true,
highlight: true,
minlength: 2,
},{
name: 'users',
display:'username',
source:users.ttAdapter(),
templates: {
suggestion: function (users) {
return '<p><a href="index.php?userid='+users.CustomerId+'" style="color:inherit;text-decoration:none;width:100%">'+users.username+'</a></p>';
}
}
比如我的数据库是这样的:
1.哈雷
2.哈雷戴维森
当我在搜索框中输入“Har”时,“Harley”只显示在建议中。 “Harley Davidson”仅在我键入“Harley”时显示,末尾有空格。有人可以建议如何克服这个错误吗?
这是我的 users.php 文件
<?php
header('Content-Type:application/json');
if(!isset($_GET['query']))
{
echo json_encode([]);
exit();
}
$mysqli=new PDO("mysql:host=127.0.0.1;dbname=website","root","");
$users=$mysqli->prepare("SELECT id,username FROM users WHERE username LIKE :query");
$users->execute(['query'=>"{$_GET['query']}%"]);
echo json_encode($users->fetchAll());
?>
【问题讨论】:
-
我们能看到数据库查询发生的users.php代码吗?您是否调试过 PHP 代码以确保输入到搜索框中的内容就是查询中包含的内容?
-
@Cᴏʀʏ 我已经修改了问题并包含了 users.php 文件
-
从 url 返回的数据是什么样的?如果使用POSTMan之类的工具调用url,是否有效?
标签: jquery twitter-bootstrap autocomplete typeahead.js