Ajax案例二

搜索自动补全分析

分析:

在这里插入图片描述##### 页面 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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值