两种形式:字符串 和 ajax
jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><script type="text/javascript" src="${pageContext.request.contextPath}/js/my.js"></script><!-- 引入jquery --><script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script><script type="text/javascript">$(function(){//绑定键盘抬起事件$("#nameId").keyup(function(){//先清空大div下所有的子元素 ???empty()删除匹配的元素集合中所有的子节点。$("#content").empty();var url="${pageContext.request.contextPath}/product";//获取到文本框的值var val=$(this).val();var jsonData={"pname":val,"method":"findPname"};//发送异步的请求,获取用户输入的值,发送服务器端$.post(url,jsonData,function(data){//怎么处理//先切分var pnames=data.split(",");//编写循环for(var i=0;i<pnames.length;i++){//获取到数据var pname=pnames[i];//创建divvar $div=$("<div></div>");$div.text(pname);//创建div后,可以给div绑定事件$div.bind("mouseover",function(){$(this).css("backgroundColor","red");});$div.bind("mouseout",function(){$(this).css("backgroundColor","white");});//点击事件$div.bind("click",function(){$("#nameId").val($(this).text());//把所有小div清空$("#content").empty();});$("#content").append($div);}//让大div显示出来$("#content").show();});}); ?//使用json数据的格式 $("#nameId").keyup(function(){$("#content").empty();var url="${pageContext.request.contextPath}/product";var val=$(this).val();var jsonData={"pname":val,"method":"findPnameByJson"};$.post(url,jsonData,function(data){//data是Json对象 ?{"list":[{"pname":"编程思想2","pnum":10,"price":88}]} //获取到数组var lists=data.list;//遍历for(var i=0;i<lists.length;i++){//获取每一个商品的对象var product=lists[i];//通过属性获取值var pname=product.pname;var $div=$("<div></div>");$div.text(pname);//每创建一个div,添加一个事件$div.bind("mouseover",function(){$(this).css("backgroundColor","red");});$div.bind("mouseout",function(){$(this).css("backgroundColor","white");});//每个小div的点击事件$div.bind("click",function(){$("#nameId").val($(this).text());$("#content").empty();});$("#content").append($div);}$("#content").show();},"json");}); });</script><div id="divmenu"><ahref="${pageContext.request.contextPath}/product?method=findByPage2&category=文学">文学</a><ahref="${pageContext.request.contextPath}/product?method=findByPage2&category=生活">生活</a><ahref="${pageContext.request.contextPath}/product?method=findByPage2&category=计算机">计算机</a><ahref="${pageContext.request.contextPath}/product?method=findByPage2&category=外语">外语</a><ahref="${pageContext.request.contextPath}/product?method=findByPage2&category=经营">经管</a><ahref="${pageContext.request.contextPath}/product?method=findByPage2&category=励志">励志</a><ahref="${pageContext.request.contextPath}/product?method=findByPage2&category=社科">社科</a><ahref="${pageContext.request.contextPath}/product?method=findByPage2&category=学术">学术</a><ahref="${pageContext.request.contextPath}/product?method=findByPage2&category=少儿">少儿</a><ahref="${pageContext.request.contextPath}/product?method=findByPage2&category=艺术">艺术</a><ahref="${pageContext.request.contextPath}/product?method=findByPage2&category=原版">原版</a><ahref="${pageContext.request.contextPath}/product?method=findByPage2&category=科技">科技</a><ahref="${pageContext.request.contextPath}/product?method=findByPage2&category=考试">考试</a><ahref="${pageContext.request.contextPath}/product?method=findByPage2&category=生活百科">生活百科</a><a href="${pageContext.request.contextPath}/product?method=findByPage" style="color:#FFFF00">全部商品目录</a></div><div id="divsearch"><form action="${pageContext.request.contextPath}/" method="post"><table width="100%" border="0" cellspacing="0"><tr><td style="text-align:right; padding-right:220px"><!-- 完成案例 -->Search <input type="text" name="name" class="inputtable" ?id="nameId" /> <input type="image" src="images/serchbutton.gif" border="0" style="margin-bottom:-4px"></td></tr></table></form></div><!-- 现在是隐藏的,用来存储书的名称的 --> <div id="content" style="background-color:white;width:128px; text-align:left;margin-left:859px;color:black;float:left;margin-top: -20px;display: none"><!-- 显示提醒 --><div></div><div></div></div>
ProductServlet:
/** * 异步的方式获取图书的名称 * @param request * @param response * @throws ServletException * @throws IOException */public void findPname(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获取请求的参数String pname=request.getParameter("pname");//假如书的名称是空的if(pname==null || pname.trim().isEmpty()){return;}//通过图书的名称去查询数据库ProductService ps=new ProductService();List<Object> list=ps.findPname(pname);//如果没有查询到结果if(list==null || list.size()==0){return;}StringBuffer sb=new StringBuffer();//响应的字符串for(Object str:list){sb.append(str);sb.append(",");}//数据 =编程思想,故事会,核心技术,String msg=sb.toString();//去掉末尾的(也可以不去)msg=msg.substring(0,msg.length()-1);//响应字符串response.getWriter().print(msg);}/** * 使用json的方式获取图书的 * @param request * @param response * @throws ServletException * @throws IOException */public void findPnameByJson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String pname=request.getParameter("pname");if(pname==null || pname.trim().isEmpty()){return; }ProductService ps=new ProductService();//通过商品的名称,查询符合名称的所有所有商品List<Product> list=ps.findPnameByJson(pname);//使用Jsonlib的工具类,把list转成Json字符串//使用jsonObjectJSONObject j=new JSONObject();j.put("list", list);//生成字符串String result=j.toString();//{"list":[{"category":"计算机","description":"这书比较难!","imgUrl":"","pid":"e865ad86-7ae7-4ce5-84a3-8df890895b71","pname":"编程思想2","pnum":10,"price":88}]}System.out.println(result);response.getWriter().print(result);}
ProductService:
/** * 通过用户输入的图书名称查找图书 * @param pname * @return */public List<Object> findPname(String pname) {ProductDao dao=new ProductDao();return dao.findPname(pname);}/** * 通过商品的名称,查询符合名称的所有所有商品 * @param pname * @return */public List<Product> findPnameByJson(String pname) {ProductDao dao=new ProductDao();return dao.findPnameByJson(pname);}
ProductDao:
/** * 通过用户输入的图书名称查找图书 * @param pname * @return */public List<Object> findPname(String pname) {QueryRunner runner=new QueryRunner(MyJdbcUtils.getDataSource());String sql="select pname from products where pname like ?";try {return runner.query(sql, new ColumnListHandler(),pname+"%");} catch (SQLException e) {e.printStackTrace();throw new RuntimeException(e);}}//通过商品的名称,查询符合名称的所有所有商品public List<Product> findPnameByJson(String pname) {QueryRunner runner=new QueryRunner(MyJdbcUtils.getDataSource());String sql="select * from products where pname like ?";try {return runner.query(sql, new BeanListHandler<Product>(Product.class),pname+"%");} catch (SQLException e) {e.printStackTrace();throw new RuntimeException(e);}}
31.jquery的ajax异步实现搜索提示栏
原文地址:https://www.cnblogs.com/syj1993/p/8467404.html