码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-10-25 09:20:56      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:ajax   jquery   jquery ajax   自动补全   

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


CSS

<style type="text/css" >
.listbox{
position: relative;
left: 10px;
margin: 10px;
width: 200px;
background-color: #000;
color: #fff;
border: 2px solid #000; 
}

.nameslist{
margin: 0px;
padding: 0px;
list-style: none;
}

.hover{
background-color: cyan;
color: red;
}

</style>

js

<script type="text/javascript">
$(document).ready(function(){
     $('.listbox').hide();
     $('.userid').keyup(function(){
	    var user = $('.userid').val();
	    var data = 'username='+user;
	    $.ajax({
	        type:"POST",
	        url:"AutoServlet",
	        data:data,
	 		success:function(html){
	  			$('.listbox').show();
	  			$('.nameslist').html(html);
	  			$('li').hover(
	  				function(){
	  	 				 $(this).addClass('hover');
	  				},
	  				function(){
	  					 $(this).removeClass('hover');
	  				}
	  			);
	    		$('li').click(function(){
	     			 $('.userid').val($(this).text());
	     			 $('.listbox').hide();
	    		});
	 	   }	
		});
		return false;
	});
});

</script>

HTML元素

<form>
  <span class="label">Enter username</span>
  <input type="text" name="userid" class="userid"/>
  <div class="listbox">
  	<div class="nameslist">
  	</div>
  </div>
</form>


后台servlet

/**
 * @author fcs
 * AutoComplete demo
 * 2014-10-25
 */
public class AutoServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String sname = request.getParameter("username");
		System.out.println("sname:"+sname);
		PrintWriter pw = response.getWriter();
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
			PreparedStatement ps = con.prepareStatement("select name from auto where name like '%"+sname+"%'");
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				pw.print("<li>"+rs.getString("name")+"</li>");
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}


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

标签:ajax   jquery   jquery ajax   自动补全   

原文地址:http://blog.csdn.net/fcs_learner/article/details/40439393

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!