<body>
<!--
1、获取搜索框并为其添加用户输入事件
2、获取用户输入的关键字
3、向服务器端发送请求并携带关键字作为请求参数
4、将响应数据显示在搜索框底部
-->
<div class="container">
<div class="form-group">
<input type="text" class="form-control" placeholder="请输入搜索关键字" id="search">
<ul class="list-group" id="list-box">
</ul>
</div>
</div>
<script src="/js/ajax.js"></script>
<script src="/js/template-web.js"></script>
<script id="tpl" type="text/html">
<!-- 循环 -->
{{each result}}
<li class="list-group-item">{{$value}}</li>
{{/each}}
</script>
<script>
var searchInp = document.getElementById('search');
var listBox = document.getElementById('list-box');
var time = null;
searchInp.oninput = function() {
clearTimeout(time);
var key = this.value;
if (key.trim().length == 0) {
listBox.style.display = 'none';
return;
}
time = setTimeout(function() {
ajax({
type: 'get',
url: 'http://localhost:3000/searchAutoPrompt',
data: {
key: key
},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: function(result) {
var html = template('tpl', {
result: result
});
listBox.innerHTML = html;
listBox.style.display = 'block';
},
error: function() {}
})
}, 800)
};
</script>
</body>
app.get('/searchAutoPrompt', (req, res) => {
var key = req.query.key;
const list = [
'黑马程序员',
'黑马程序员官网',
'黑马程序员顺义校区',
'黑马程序员学院报名系统',
'传智播客',
'传智博客前端与移动端开发',
'传智播客大数据',
'传智播客python',
'传智播客java',
'传智播客c++',
'传智播客怎么样'
];
let result = list.filter(item => item.includes(key));
res.send(result);
})