jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(function(){
//文本框keyup的时候发送ajax
$("#tid").keyup(function(){
//获取文本框的值
var $value=$(this).val();
//内容为空的时候不发送ajax
if($value!= null && $value!=''){
//清空div
$("#did").html("");
$.post("/day15/searchKw","kw="+$value,function(d){
//不为空的时候切割字符串
if(d!=''){
var arr=d.split(",");
$(arr).each(function(){
//alert(this);
//可以将每一个值放入一个div 将其内部插入到id为did的div中
$("#did").append($("<div>"+this+"</div>"));
});
//将div显示
$("#did").show();
}
});
}else{
//内容为空的时候 将div隐藏
$("#did").hide();
}
});
})
</script>
<title>Insert title here</title>
</head>
<body>
<center>
<div>
<h1>黑马搜索</h1>
<div>
<input name="kw" id="tid"><input type="button" value="黑马一下">
</div>
<div id="did" style="border: 1px solid red;width: 171px;position:relative;left:-34px;display:none"></div>
</div>
</center>
</body>
</html>
servlet代码:
package com.itheima.web.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itheima.service.KeyWordService;
/**
* 模仿百度 模糊
*/
public class SearchKwServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//0.设置编码
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
//1.获取kw
String kw=request.getParameter("kw");
//2.调用service完成模糊操作 返回值:list
List<Object> list=null;
try {
list = new KeyWordService().findKw4Ajax(kw);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//3.将数据 [a,aa,aaa] 去掉括号 写回去 a,aaa,aa
if(list!=null && list.size()>0){
String s = list.toString();
s=s.substring(1, s.length()-1);
System.out.println(s);
response.getWriter().println(s);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
网友评论