搜索自动补全分析
分析:
##### 页面 jQuery部分
<script type="text/javascript">
function search() {
var proId = $("#proID");
//获取搜索框内容
var word = $("#word").val();
if(word.trim()=="") {
proId.hide();
return;
}
$.get(
"/WEB11_store/search",
"word="+word,
function(data){
//div显示出来
proId.show();
//定义字符串,拼接商品名
var s = "";
//data回来的JSON,是个数组
$.each(data,function(index,element){
//element就是遍历的数组元素,元素是对象
//alert((element.pname));
s+= "<div οnmοuseοut='out(this)' οnmοuseοver='over(this)' style='border-bottom: 1px solid #909090'>"+ element.pname + "</div>";
});
proId.html(s);
},"json"
);
}
function over(obj) {
$(obj).css("background-color","yellow");
}
function out(obj) {
$(obj).css("background-color","#FFFFFF");
}
</script>
dao 数据访问层
/**
* 根据商品名模糊查询
* 业务层传递商品名
* 返回集合List
*/
public List<Product> search(String word) throws SQLException {
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
String sql = "select * from product where pname like ?";
return qr.query(sql,new BeanListHandler<Product>(Product.class), "%"+word+"%");
}
service 业务层
/**
* 商品关键字查询
* Web层传递商品名
* 调用dao层,传递商品名
* 获取结果集合
*
* @param word
* @return
*/
public List<Product> search(String word){
List<Product> productList = null;
ProductDao productDao = new ProductDao();
try {
productList = productDao.search(word);
} catch (SQLException e) {
e.printStackTrace();
}
return productList;
}
web 层
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* 获取客户端提交商品名
* 调用业务层传递商品名
* 获取查询结果List集合
* 集合转成JSON数据格式
* 响应客户端
*/
String word = request.getParameter("word");
ProductService service = new ProductService();
List<Product> list = service.search(word);
//集合对象转成JSON格式数据
Gson gson = new Gson();
String json = gson.toJson(list);
System.out.println(json);
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(json);
}