ajax搜索框内容自动提示
1.服务器端代码
// 引入express框架
const express = require('express');
// 路径处理模块
const path = require('path');
const formidable = require('formidable');
// 创建web服务器
const app = express();
// 静态资源访问服务功能
app.use(express.static(path.join(__dirname, 'public')));
// 输入框文字提示
app.get('/searchAutoPrompt', (req, res) => {
// 搜索关键字
const key = req.query.key;
// 提示文字列表
const list = [
'黑马程序员',
'黑马程序员官网',
'黑马程序员顺义校区',
'黑马程序员学院报名系统',
'传智播客',
'传智博客前端与移动端开发',
'传智播客大数据',
'传智播客python',
'传智播客java',
'传智播客c++',
'传智播客怎么样'
];
// 搜索结果
let result = list.filter(item => item.includes(key));
// 将查询结果返回给客户端
res.send(result);
});
// 监听端口
app.listen(3000);
// 控制台提示输出
console.log('服务器启动成功');
2.客户端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>搜索框输入文字自动提示</title>
<link rel="stylesheet" href="./assets/bootstrap/dist/css/bootstrap.min.css">
<style type="text/css">
.container {
padding-top: 150px;
}
.list-group {
display: none;
}
</style>
</head>
<body>
<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 type="text/html" id="tpl">
{{each result}}
<li class="list-group-item">{{$value}}</li>
{{/each}}
</script>
<script>
//获取搜索框
var searchInp = document.getElementById('search');
//获取提示文字的存放容器
var listBox = document.getElementById('list-box');
//存储定时器的变量
var timer = null;
//当用户在文本框中输入的时候触发
searchInp.oninput = function() {
// console.log(1);
//获取用户输入的内容
var key = this.value;
//如果用户没有在搜索框中输入内容
if (key.trim().length == 0) {
//将提示下拉框隐藏掉
listBox.style.display = 'none'
return;
}
//向服务器端索取和用户输入关键字相关的内容
timer = setTimeout(function() {
//清除上一次开启的定时器
clearTimeout(timer);
ajax({
type: 'get',
url: 'http://localhost:3000/searchAutoPrompt',
data: {
key
},
success: function(result) {
var html = template('tpl', {
result: result
});
//将拼接好的字符串显示在页面中
listBox.innerHTML = html;
//显示ul容器
listBox.style.display = 'block'
}
})
}, 800)
}
</script>
</body>
</html>