一个模拟搜索自动补全的实例(超简单)

前端之家收集整理的这篇文章主要介绍了一个模拟搜索自动补全的实例(超简单)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

很早就像写一个模拟Google搜索自动补全的实例,那时候刚学点js,css也玩不转,即使网上有些demo,看起来也很费力。写了两次只是勉强能出来待筛选项,不能自由选择。这两天学了点jQuery的ajax,配合一点资料,自己成功实现了这个功能,jQuery的口号真是名副其实----The Write Less,Do More.


CSS

  1. <style type="text/css" >
  2. .listBox{
  3. position: relative;
  4. left: 10px;
  5. margin: 10px;
  6. width: 200px;
  7. background-color: #000;
  8. color: #fff;
  9. border: 2px solid #000;
  10. }
  11.  
  12. .nameslist{
  13. margin: 0px;
  14. padding: 0px;
  15. list-style: none;
  16. }
  17.  
  18. .hover{
  19. background-color: cyan;
  20. color: red;
  21. }
  22.  
  23. </style>

js
  1. <script type="text/javascript">
  2. $(document).ready(function(){
  3. $('.listBox').hide();
  4. $('.userid').keyup(function(){
  5. var user = $('.userid').val();
  6. var data = 'username='+user;
  7. $.ajax({
  8. type:"POST",url:"AutoServlet",data:data,success:function(html){
  9. $('.listBox').show();
  10. $('.nameslist').html(html);
  11. $('li').hover(
  12. function(){
  13. $(this).addClass('hover');
  14. },function(){
  15. $(this).removeClass('hover');
  16. }
  17. );
  18. $('li').click(function(){
  19. $('.userid').val($(this).text());
  20. $('.listBox').hide();
  21. });
  22. }
  23. });
  24. return false;
  25. });
  26. });
  27.  
  28. </script>

HTML元素

  1. <form>
  2. <span class="label">Enter username</span>
  3. <input type="text" name="userid" class="userid"/>
  4. <div class="listBox">
  5. <div class="nameslist">
  6. </div>
  7. </div>
  8. </form>


后台servlet

  1. /**
  2. * @author fcs
  3. * AutoComplete demo
  4. * 2014-10-25
  5. */
  6. public class AutoServlet extends HttpServlet {
  7. @Override
  8. protected void service(HttpServletRequest request,HttpServletResponse response)
  9. throws ServletException,IOException {
  10. String sname = request.getParameter("username");
  11. System.out.println("sname:"+sname);
  12. PrintWriter pw = response.getWriter();
  13. try {
  14. Class.forName("com.MysqL.jdbc.Driver");
  15. Connection con = DriverManager.getConnection("jdbc:MysqL://localhost:3306/test","root","root");
  16. PreparedStatement ps = con.prepareStatement("select name from auto where name like '%"+sname+"%'");
  17. ResultSet rs = ps.executeQuery();
  18. while(rs.next()){
  19. pw.print("<li>"+rs.getString("name")+"</li>");
  20. }
  21. } catch (ClassNotFoundException e) {
  22. e.printStackTrace();
  23. } catch (sqlException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }


1.输入一个字母a,自动触发数据库检索,然后将结果返回到页面


2.鼠标悬浮效果


3.点击选中结果:

猜你在找的Ajax相关文章