AJAX(DWR框架) 实现搜索自动补全 类似google,baidu
1. DAO里写好根据商品名模糊查找,返回一个String[] 数组 的方法 public String[] findbyname(String name){ Session sess=HibernateSessionFactory.getSession(); String [] goodsname = null; try { String hql="select a from TGoods a where a.goodsnum-a.sellnum>0 and a.goodsname like '%"+name+"%' order by a.scannum desc"; Query q=sess.createQuery(hql); q.setFirstResult(0); q.setMaxResults(8); List list=q.list(); if(!list.isEmpty()){ List<TGoods> g = list; goodsname = new String [g.size()]; for (int i=0;i<list.size();i++) { goodsname[i] = g.get(i).getGoodsname(); //把商品名字放到数组里 } } } catch (Exception e) { e.printStackTrace(); }finally{ HibernateSessionFactory.closeSession(); return goodsname; } } 2.配置DWR.XML (具体请看http://hi.baidu.com/stream1990/blog/item/ca6d330665afbec77b8947c3.html) <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://www.getahead.ltd.uk/dwr/dwr20.dtd" > <!-- <!DOCTYPE dwr SYSTEM "dwr20.dtd" > --> <dwr> <allow> <create creator="new" javascript="findbyname"> <param name="class" value="com.dao.TGoodsDAO" /> </create> </allow> </dwr> 3.最重要的来了,很多人可能都卡在这了吧 <script type='text/javascript' src='/shops/dwr/interface/findbyname.js'></script> <script type='text/javascript' src='/shops/dwr/engine.js'></script> <script type='text/javascript' src='/shops/dwr/util.js'></script> <script> function gog() { var keys = document.getElementById("keys").value; findbyname.findbyname(keys,call1); } function call1(data) { if(data!=null){ //当查询结果没数据时,不写这句会报错的 var keys = document.getElementById("keys").value; keys=keys.replace(/(^\s*)|(\s*$)/g,""); //这个是去掉空格,正则功能很强大的 if(keys != ""){ //如果不判断,一按下键就会有8条数据 document.getElementById("tishi").innerHTML = ""; for(var i=0;i<data.length;i++){ document.getElementById("tishi").innerHTML+="<div onclick=" + "document.getElementById('keys').value=this.innerText" + " onmouseout=" + "this.style.backgroundColor=''"+ " onmouseover=" + "this.style.backgroundColor='#3266CC'>" +data[i] + "</div>" ; //写这语句的时候小心,别写错了 } }else{ document.getElementById("tishi").innerHTML = ""; } }else{ document.getElementById("tishi").innerHTML = ""; } } </script> 这样就OK了,实现并不难,但做的时候心要很细,最后,还有一点,baidu,google是从第一个字开始匹配,但我加的测试数据不多,所以用了两个%关键字% ,要想做的和baidu,google一们,只要HQL那里改成 关键字% 就可以了,还有,用键盘的上下键功能用javascript就可以实现,这里没做, 哦,对了,还有静态页面,里头触发事件用的是onkeyup ,还有几个类似功能的也可以 <TABLE cellPadding=4 width="100%" border=0> <tr> <td valign="top">关键字:</td> <td> <table> <tr> <td><input type="text" name=goodsname id="keys" onkeyup="gog()" size="60"></td> </tr> <tr> <td bgcolor="#F6F6EE"><div id="tishi" ></div></td> </tr> </table> </td> </tr> </table> |
相关推荐
Eric实验室 2014-01-25
dengcanjun 2015-07-05
logocvv 2013-11-18
tansybigrabbit 2012-03-01
MayMatrix 2009-01-21
Drxin 2016-01-28
huangxb00 2015-10-27
mannoroth 2011-03-30
huanglianhuabj00 2014-12-25
del 2011-03-18
tomatoboryj 2011-03-14
MusicPeng 2014-11-20
mannoroth 2011-01-06
mofgeng 2010-12-19
del 2014-01-25
del 2010-09-01
lisongchuang 2013-07-16