JQuery、Servlet实现页面值的动态变化

本功能实现了购物车中根据checkbox选中的情况动态计算被选中商品的件数和商品的总价

1、Jsp页面

<table id="carttable">
<tr>
<th><input class="allcheck" type="checkbox">全选</th>
<th>图片</th>
<th>书名</th>
<th>作者</th>
<th>单价</th>
<th>剩余数量</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<c:set var="i" value="0"/>
<c:forEach var="entry" items="${cart.map}">
<c:set var="i" value="${i+1}"/>
<tr>
<td width="50px"><input type="checkbox" name="item${i}" class="checkcell"></td>
<td><a href="BuyServlet?id=${entry.value.book.bookID}" class="pagelink"><img class="image" src="${pageContext.request.contextPath }${entry.value.book.imagePath}"></a></td>
<td>${entry.value.book.bookName}</td>
<td>${entry.value.book.bookAuthor}</td>
<td class="price">${entry.value.book.bookPrice}</td>
<td>${entry.value.book.bookQuantity}</td>
<td class="buynum">${entry.value.buyQuantity}</td>
<td><a href="#">删除</a></td>
</tr>
</c:forEach>
</table>
<table id="paytable">
<tr>
<td width="5%" align="center"><input type="checkbox" class="allcheck1">全选<td>
<td width="5%" align="center"><a href="#">删除</a></td>
<td width="60%" align="right">已选书籍数</td>
<td width="5%" align="center" id="buyNumTD">0</td>
<td width="5%" align="left">本</td>
<td width="10%" align="right">总计:</td>
<td width="5%" align="center" id="priceTD">0.00</td>
<td width="5%" align="left">元</td>
<td><input type="button" value="结算" id="payment"></td>
</tr>
</table>

显示的图片如下:

2、通过jquery动态的将选中的值传给servlet

<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript">
$(function()
        {
          var buynum;
          var price;
           $(":checkbox").click(function(){//checkbox触发点击属性
            //判断checkall的属性checked的值是否是checked。
            //如果是所有的选项框都打上对号
            //如果不是,将所有的选项框的对号清空
                buynum=[0];
                price=[0];
                var i=0;
                var allcheckLength=$(".allcheck[checked='checked']").length;
                alert(allcheckLength)
                if(allcheckLength==0)//全选框没被选中时,点击全选框,所有的checkbox都被选中
                {
                $(".allcheck").each(function(){
                    if($(this).prop("checked")==true)
                        {
                        $("input:checkbox").attr("checked","checked");
                        $("input:checkbox").prop("checked",true);
                       
                        }
                });
                }else if(allcheckLength==2)//全选框被选中时,点击全选框取消选中
                    {
                    $(".allcheck").each(function(){
                        if($(this).prop("checked")==false)
                            {
                            $("input:checkbox").removeAttr("checked");
                            $("input:checkbox").prop("checked",false);
                            }
                                  });
                    }
                $(".checkcell").each(function()//遍历每个.checkcell的checkbox
                              {
                        if($(this).prop("checked")==true)
                            {
                         $(this).attr("checked","checked");
                           buynum[i]=$(this).parent().parent().find(".buynum").text();
                           price[i]=$(this).parent().parent().find(".price").text();
                           i++;
                            }
                        else
                            {
                            $(this).removeAttr("checked");
                            }
                              });
              //子checkbox全选中,allcheckbox全选中;子checkbox任意一个取消选中,allcheckbox取消选中。
             var checkedLength=$(".checkcell[checked='checked']").length;
                var subLength=$(".checkcell").length;
                alert(checkedLength);
                //如果所有的子checkbox个数不等于选中的checkbox的个数,就取消全选框的对号
                if(subLength!=checkedLength)
                    {
                    if(allcheckLength==2)
                    {
                    $(".allcheck").each(function()
                            {
                        $(this).prop("checked",false);
                        $(this).removeAttr("checked");
                            });
                    }
                    }
                else
                    {//如果所有的子checkbox被选中,全选框也全选中
                    $(".allcheck").each(function()
                            {
                        $(this).prop("checked",true);
                        $(this).attr("checked","checked");
                            });
                    }
            postService(buynum,price);
             
        });
      //以上程序的功能是完成复选框选中或取消之间的逻辑关系,已经获得被选中书籍的购买数和价格的拼接字符串,将拼接的字符串传给servlet,然后进行处理
       
      });
    
function postService(buynum,price)
{
     $.post("ComputeServlet",{'buynum':buynum.join(","),'price':price.join(",")},
             function(returnedData,status)
             {
             var result1=$(returnedData).find("buyNum").text();
             var result2=$(returnedData).find("totalPrice").text();
             
             $("#buyNumTD").text(result1);
             $("#priceTD").text(result2);

});
     }        
</script>
3、Servlet的处理类,将接受到的参数进行转化,计算出的结果再转化为XML的格式或者JSON的格式传给前端的$.post中的returnedData。这样做的目的是便于操作。

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String buynum=request.getParameter("buynum");
		String price=request.getParameter("price");

		String[] buyNumString=buynum.split(",");
		String[] priceString=price.split(",");
		int buyBookNum=0;
		double totalPrice=0.00;
		for(int i=0;i<buyNumString.length;i++)
		{
			buyBookNum+=Integer.parseInt(buyNumString[i]);
			totalPrice+=(Double.parseDouble(priceString[i]))*(Integer.parseInt(buyNumString[i]));
		}
		System.out.println("buyBookNum"+buyBookNum);
		System.out.println("totalPrice"+totalPrice);
		
		Document document=DocumentHelper.createDocument();
		Element rootElement=document.addElement("result");
		Element buyNumElement=rootElement.addElement("buyNum");
		Element totalPriceElement=rootElement.addElement("totalPrice");
                buyNumElement.setText(buyBookNum+"");
                totalPriceElement.setText(totalPrice+"");
		
                response.setContentType("text/xml;charset=utf-8");
		response.setHeader("pragma","no-cache");
		response.setHeader("cache-control", "no-cache");
		PrintWriter out=response.getWriter();
		OutputFormat format=OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		
		XMLWriter xmlWriter=new XMLWriter(out,format);
		xmlWriter.write(document);
		out.flush();
	}

4、运行的结果如下:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值