Ajax--案例(搜索框内容自动提示)用到template-web模板,bootstrap框架,setTimeout定时器,ajax封装函数

接口文档:

 .html文件:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>搜索框内容自动提示</title>
 6     <link rel="stylesheet" type="text/css" href="/assets/bootstrap/dist/css/bootstrap.min.css">
 7     <style type="text/css">
 8         .container{
 9             padding-top:150px;
10         }
11         .list-group{
12             display: none;
13         }
14     </style>
15 </head>
16 <body>
17     <div class="container">
18         <div class="form-group">
19             <input type="text" class="form-control" placeholder="请输入搜索关键字" id="search">
20             <ul class="list-group" id="list-box">
21                 
22             </ul>
23         </div>
24     </div>
25 
26     <!-- script -->
27     <script src="/js/ajax.js"></script>
28     <script src="/js/template-web.js"></script>
29     <script type="text/html" id="tpl">
30         {{each result}}
31         <li class=list-group-item>{{$value}}</li>
32         {{/each}}    
33     </script>>
34     <script type="text/javascript">
35         //获取搜索框  searchInp
36         var searchInp=document.getElementById('search');
37         //获取提示文字的存放文字  listBox
38         var listBox=document.getElementById('list-box');
39 
40         //存储定时器的变量
41         var timer=null;
42 
43         //当用户在文本框中输入的时候触发 s.oninput=function()
44         searchInp.oninput=function(){
45             //清除上一次开启的定时器
46             clearTimeout(timer);
47 
48             //获取用户输入的内容 key =this.value(s.value)
49             var key=this.value;
50             //如果用户没有再搜索框中输入内容
51             if(key.trim().length==0){
52                 //将提示下拉框隐藏掉
53                 listBox.style.display="none";
54                 //阻止程序向下执行
55                 return;
56             }
57             timer=setTimeout(function(){
58                 //向服务器端发送请求
59             //向服务器端索取和用户输入关键字相关的内容
60             ajax({
61                 type:'get',
62                 url:'http://localhost:3000/searchAutoPrompt',
63                 data:{
64                     key:key
65                 },
66                 success:function(result){
67                     //console.log(result);
68                     //使用模板引擎拼接字符串
69                     var html1=template("tpl",{result:result})
70                     //将拼接好的字符串显示在页面中
71                     listBox.innerHTML=html1;
72                     //显示ul容器
73                     listBox.style.display="block";
74                 }
75             })
76         },800)
77             
78         }            
79     </script>
80 </body>
81 </html>

未输文字前:

 输入提示文字后:

猜你喜欢

转载自www.cnblogs.com/technicist/p/12752326.html