我正在按照此webpage教程使用Typeahead.js从MYSQL数据库填充输入框
Server.js
const pool=mysql.createPool({
connectionLimit:10,
host:'localhost',
user:'user',
password:'password',
database:'table'
})
router.get("/",(req,res)=>{
res.render("home")
})
router.get('/search',function(req,res){
pool.query('SELECT tableName from parts where tableName like "%'+req.query.key+'%"',
function(err, rows, fields) {
if (err) throw err;
var data=[];
for(i=0;i<rows.length;i++)
{
data.push(rows[i].tableName);
}
res.end(JSON.stringify(data));
});
});
home.ejs
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="typehead.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input.typeahead').typeahead({
name: 'typeahead',
remote: 'http://localhost:3000/search?key=%QUERY',
limit: 10
});
});
</script>
</head>
<body>
<input class="typeahead tt-query" spellcheck="false" autocomplete="off" name="typeahead" type="text" />
typeahead.js库已正确加载,并且在我的Google chrome控制台中看不到任何错误。我的数据库也已正确连接,因为我还有其他路由可以访问连接池,该连接池工作正常。本地路由正在加载搜索栏,但是,当我在其中键入mySQL数据库中存在的表Name时,它不会自动完成。
答案 0 :(得分:0)
根据此处的示例:http://twitter.github.io/typeahead.js/examples/,您似乎缺少构建Bloodhound对象以传递给typeahead的Source属性的功能。
他们的例子:
var bestPictures = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: '../data/films/post_1960.json',
remote: {
url: '../data/films/queries/%QUERY.json',
wildcard: '%QUERY'
}
});
$('#remote .typeahead').typeahead(null, {
name: 'best-pictures',
display: 'value',
source: bestPictures
});
对于您的脚本,我会尝试进行此更改:
<script type="text/javascript">
$(document).ready(function(){
$('input.typeahead').typeahead({
name: 'typeahead',
source: new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: '../data/films/post_1960.json',
remote: {
url: '-http://localhost:3000/search?key=%QUERY',
wildcard: '%QUERY'
}
}),
limit: 10
});
});
</script>