Ajax+Json实现百度自动补全

2 篇文章 0 订阅

search.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML>
<html>
  <head>
    <base href="<%=basePath%>">
  
    <title>My JSP 'search.jsp' starting page</title>
    
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <style type="text/css">
                #content{margin:0 auto; width: 822px; margin-top: 200px; }
                #search{height: 60px; width: 700px;margin: 0px;font-size: 30px;padding-left: 5px}
                #btn{font-size: 30px;height: 61px; width:108px;  padding:5px 5px}
                #mess{width: 700px;font-size: 30px;}

        </style>
  </head>
  
  <body>
  	 <div id="content">
           <div id="middle">
                   <input type="text" id="search" autocomplete="off" >
                   <input id="btn" type="button"  value="search">
           </div>
           <div id="mess" style="padding-left: 1px"></div>
   	 </div>
  </body>
  <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
  <script type="text/javascript">
  $(function(){
          $("#search").keyup(function(){
                var name = $(this).val();
                if(name==''){
                        return;
                }
                $("#mess").css("display","");//mess显示
                $.ajax({
                        url:"book",//请求的地址
                        type:"post",//请求方式
                        dataType:"text",//数据传输的格式
                        data:{"name":name},//传输的数据
                        success:function(ret){//处理成功的回调函数
                                $("#mess").html("");//清空div
                                var arr = ret.split(",");
                                for(var i=0;i<arr.length-1;i++){
                                        $("#mess").append("<div onmouseover='mouseover(this)' onmouseout='mouseout(this)' onclick='cli(this)'>"+arr[i]+"</div>");	
                                }				
                        },
                        error:function(){//处理失败的回调函数
                                alert("请求异常");
                        }
                }); 
                });
  });
  function mouseover(t){
        t.style.backgroundColor="red";  
  }
  function mouseout(t){
        t.style.backgroundColor="white";  
  }
  
  function cli(t){
        var value = t.innerHTML;
        $("#search").val(value);
        $("#mess").css("display","none");//mess隐藏
  }
  </script>
</html>

BookServlet_json.java

@WebServlet("/book_json")
public class BookServlet_json extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			
			String name = request.getParameter("name");
			String sql="select name from tb_book where name like '%"+name+"%'";
			JdbcUtil jdbc = new JdbcUtil();
			ResultSet rs = jdbc.query(sql, null);
			List list = new ArrayList();
			while(rs.next()){
				//list.add(new Book(rs.getString(1)));
				list.add(rs.getString(1));
			}
			/**
			 *  {"name":"zhangsan","age":20} 
			 *  [{"name":"zhangsan","age":20},{"name":"lisi","age":25}]  
			 *  ["zhangsan","lisi"]
			 */
			JSONArray json = JSONArray.fromObject(list);
			System.out.println(json);
			response.getWriter().print(json);
			jdbc.close();
		}catch(Exception e){
			
		}
	}
}

普通非json则:
BookServlet.java

@WebServlet("/book")
public class BookServlet extends HttpServlet {
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       	 try{
       	 request.setCharacterEncoding("UTF-8");
       	 response.setCharacterEncoding("UTF-8");
        
        	String name = request.getParameter("name");
       	String sql="select name from tb_book where name like '%"+name+"%'";
        	//JdbcUtil是自写工具类
	JdbcUtil jdbc = new JdbcUtil();
        	ResultSet rs = jdbc.query(sql, null);
        	String names = "";
        	while(rs.next()){
                	names+=rs.getString(1)+",";
       	 }
        	response.getWriter().print(names);
        	jdbc.close();//关闭jdbc,否则会报数据库连接用完
       	 }catch(Exception e){
       	 e.printStackTrace();
        	}
        }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值