站内查询的实现
jsp页面:
<form class="navbar-form navbar-right" role="search">
<div class="form-group" style="position:relative">
<input id="search" type="text" class="form-control" placeholder="Search" onkeyup="searchWord(this)"></input>
<div id="showDiv" style="display:none;position:absolute;z-index:1000;background:#fff;width:179px;border:1px solid #ccc;">
</div>
</div>
<buton y=type="submit" class="btn btn-default">Submit</button>
</form>
<!--完成异步搜索功能-->
<script type="text/javascript">
function overFn(obj){
$(obj).css("background","#DBEAF9");
}
function outFn(obj){
$(obj).css("background","#fff");
}
function clickFn(obj){
$("#search").val($(obj).html());
$("#showDiv").css("display","none");
}
function searchWord(obj){
//1.获得输入框输入的内容
var word=$(obj).val();
//2.根据输入框的内容去数据库中模糊查询----List<product>
var content=" ";
$.get(
"${pageContext.request.contextPath}/searchWord",
{"word":word},
function(data){
//3.将返回的商品名称显示在showDiv中
if(data.length>0){
for(var i=0;i<data.length;i++){
content+="<div syle='padding:5px;cursor:pointer' onclick='clickFn(this)' onmouseover='overFn(this)' onmouseout='outFn(this)'>"+data[i]+"</div>";
}
$("#showDiv").html(content);
$("#showDiv").css("display","block");
}
},
"json"
);
}
服务端:
//获得关键字
String word=request.getParameter("word");
//查询该关键字的所有商品
ProductService service=new ProductService();
List<Object> productList=null;
try{
productList=service.findProductByWord(word);
}catch(SQLException e){
e.printStackTrace();
}
//查出来的数据转成json格式,使用json工具将对象或者集合转换成json格式的字符串
/*JsonArray fromObject=JsonArray.fromObject(productList);
String string=fromObject.toString();
System.out.println(string);*/ //jsonlib转换插件
Gson gson=new Gson();
String json=gson.toJson(productList);
System.out.println(json);
response.setContentType("text/html;charset=UTF-8");
//结果返回给页面
response.getWriter().writer(json);
注意:
Dao层方法中查询数据的数量限制:
String sql="select * from pname like ? limit 0,8";
(%+word+%)