仿百度搜索 知识点AJAX

搜索页面   search.jsp    记得引入jquery

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<style>
.result{border:1px solid green;width:50px}
</style>
  </head>
  
  <body>
   <div class="search">
<input type="text" name="title" id="searchtitle"/>
<input type="button" value="搜索" id="searchsub"/>
<div id="result">
</div>
</div>
<c:out value="仿百度智能查询"></c:out>
  </body>
  <script type="text/javascript">
  $(function(){
	$("#searchtitle").keyup(function(){
		$("#result").css("display","none");//隐藏结果提示
		var title=$(this).val();//获取查询的内容
		setTimeout(function(){
			var url="AjaxServlet2?on=tips";//异步加载servlet
			$.post(url,{title:title},function(data){
				$("#result").empty();//清除查询内容
				if(data.length==0){
				   $("#result").css("display","none");
				   return;
				}
				//判断结果是否是空
				if(data.length!=0){
					var arr=data.split(",");//这里对刚刚拼接的字符串进行截取
					for(var i=0;i<arr.length;i++){
						$("#result").append("<div class='tips'>"+arr[i]+"</div>");
					}
					//结果提示
					//$("#result").css("display","block");
					$("#result").fadeIn("slow");//淡入slow,fast,淡出fadeOut
					$("#result").addClass("result");
					//点击tip添加到输入框
					$(".tips").click(function(){
						var text=$(this).text();
						$("#searchtitle").val(text);
						$("#result").css("display","none");
					});
				}
			});
		},500);//延迟加载时间
 
	});
});

</script>
</html>

然后Servlet

package com.test.mail;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.test.utils.DBUtil;

public class AjaxServlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public AjaxServlet2() {
		super();
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String title=request.getParameter("title");
		PrintWriter out=response.getWriter();
		//默认最多出现5条数据 看你的需求  
		String sql="select name from items where name like'%"+title+"%' limit 5";
		try {
			Connection conn=DBUtil.getConnection();
			PreparedStatement ps=conn.prepareStatement(sql);
			ResultSet rs=ps.executeQuery();
			StringBuffer sb=new StringBuffer();
			while(rs.next()){
				//这里拼接成字符串
				sb.append(rs.getString(1)+",");
			}
			//sb.substring(0,(sb.length()-1))是一个String类型的;
			if(sb.length()>0){
				out.print(sb.substring(0,(sb.length()-1)));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.flush();
		out.close();

	}
}

数据库:

/*
Navicat MySQL Data Transfer

Source Server         : test
Source Server Version : 50558
Source Host           : localhost:3306
Source Database       : testdriver

Target Server Type    : MYSQL
Target Server Version : 50558
File Encoding         : 65001

Date: 2018-09-24 13:21:30
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `items`
-- ----------------------------
DROP TABLE IF EXISTS `items`;
CREATE TABLE `items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of items
-- ----------------------------
INSERT INTO `items` VALUES ('1', '张三');
INSERT INTO `items` VALUES ('2', '张良');
INSERT INTO `items` VALUES ('3', '张衡');
INSERT INTO `items` VALUES ('4', '张恒');
INSERT INTO `items` VALUES ('5', '马云');
INSERT INTO `items` VALUES ('6', '马致远');
INSERT INTO `items` VALUES ('7', '马化腾');
INSERT INTO `items` VALUES ('8', '李宁');

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LoneWalker、

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值