Chinaunix首页 | 论坛 | 博客
  • 博客访问: 109061
  • 博文数量: 40
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 423
  • 用 户 组: 普通用户
  • 注册时间: 2013-01-15 11:55
文章分类

全部博文(40)

文章存档

2016年(36)

2015年(2)

2013年(2)

我的朋友

分类: jQuery

2016-03-16 14:42:03

html5中autocomplete 属性规定表单是否应该启用自动完成功能,但是现实中我们还需要精确定位用户到底输入了哪些关键字,从而把他存到数据库中,然后从数据库中读取,本例就是用jquery实现的下拉提示功能

点击(此处)折叠或打开

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <script src=""></script>
  6. <style>
  7. #hintbox{
  8.    display:none;
  9.    width:170px;
  10.    border:1px solid;
  11.    margin-left:136px;
  12. }
  13. </style>
  14. </head>
  15. <body>
  16.  <label>请输入手机号码:</label>
  17.  <input type="text" name="phone" id="phone" class="input"/>
  18.  <div id="hintbox" style="display:none"></div>
  19. </body>
  20. <script>

  21. $(document).ready(function(){
  22.    $("#phone").keyup(function(){
  23.       $.ajax({
  24.      type:"GET",
  25.         url:"search.php?q="+$("#phone").val()+"&timeStamp="+new Date().getTime(),
  26.         data:{
  27.          phone:$("#phone").val()
  28.         },
  29.          success:function(data){
  30.          $("#hintbox").html();
  31.          var arr = JSON.parse(data);
  32.          var html ="
      ";
    •          for(var i=0;i<arr.length;i++){
    •              html+="
    • " + arr[i] +"
    • ";
    •          }
    •          html += "
    "
    ;
  33.          console.log(html);
  34.          console.log($("#hintbox"));
  35.          $("#hintbox").html(html);
  36.          $("#hintbox").show();
  37.          $("#hintbox ul li").click(function(){
  38.          console.log($(this).text());
  39.          $("#phone").val($(this).text());
  40.          $("#hintbox").hide();
  41.      });
  42.      if($("#phone").val()===""){
  43.      $("#hintbox").hide();
  44.      }
  45.          }
  46.      });
  47.   });
  48. })
  49.   
  50. </script>
  51. </html>

  1. 后台代码是用php实现的search.php

点击(此处)折叠或打开

  1. <?php

  2. //获取到客户端请求参数:查询的关键字
  3. $keyword = $_GET['q'];

  4. //从数据库或缓存中模糊匹配,返回结果
  5. $a = $keyword."aaaa";
  6. $b = $keyword."bbbb";
  7. $c = $keyword."cccc";

  8. $result = array($a,$b,$c);

  9. echo json_encode($result);

  10. ?>
效果如下
阅读(828) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~