标签:ajax
页面上有一个商品的颜色尺码二维输入框,输入完毕之后需要把数据进行提交,点击立即购买则进行页面的跳转,通过form表单将数据提交到后台,而点击添加到购物车的话,则会通过ajax进行数据的提交,页面不进行跳转。前台样式:
下面是form表单:
<form id="cartForm" action="${ctx}/cart/save" method="post"> <div class="product-page-options"> <table class="table-bordered table-condensed table-hover table-advance"> <c:set var="sizeNames" value="${fn:split(product.sizeNames, ',')}" /> <c:set var="sizeIds" value="${fn:split(product.sizeIds, ',')}" /> <c:set var="colorNames" value="${fn:split(product.colorNames, ',')}" /> <c:set var="colorIds" value="${fn:split(product.colorIds, ',')}" /> <c:set var="sizesCount" value="${fn:length(sizeNames)}" /> <thead> <tr> <th class="colorStyle">颜色</th> <c:forEach items="${sizeNames}" var="sizeName" varStatus="status"> <th class="inputStyle">${sizeName}</th> </c:forEach> <th>小计</th> </tr> </thead> <tbody> <c:forEach items="${colorNames}" var="colorName" varStatus="colorsStatus"> <tr> <td class="colorStyle">${colorName}</td> <c:forEach items="${sizeNames}" var="sizeName" varStatus="status"> <c:set var="index" value="${(colorsStatus.index*sizesCount)+status.index}"/> <input type="hidden" name="items[${index}].colorId" value="${colorIds[colorsStatus.index]}"/> <input type="hidden" name="items[${index}].sizeId" value="${sizeIds[status.index]}"/> <input type="hidden" name="items[${index}].productId" value="${product.productId}"/> <td class="inputStyle"><input type="text" name="items[${index}].quantity" class="inputStyle form-control" value="${sizesCount}"/></td> </c:forEach> <td class="inputStyle">12</td> </tr> </c:forEach> <tr> <td class="colorStyle totalStyle">合计</td> <c:forEach items="${sizeNames}" var="sizeName" varStatus="status"> <td class="inputStyle totalStyle">12</td> </c:forEach> <td class="inputStyle totalStyle">24</td> </tr> </tbody> </table> </div> <div class="product-page-cart"> <button class="btn btn-primary" type="submit">立即购买</button> <input class="btn btn-primary" type="button" id="btnAddCart" value="添加到购物车"/> </div> </form>
<script type="text/javascript"> jQuery(document).ready(function() { $('input#btnAddCart').click( function() { $.ajax({ url: '${ctx}/api/v1/drp/cart/add', type: 'post', dataType: 'json', data: $('form#cartForm').serialize(), success: function(data) { alert("success!"); } }); }); }); </script>绑定input并且id是btnAddCart的按钮,也就是form里面的添加到购物车这个按钮的click事件,然后进行ajax进行提交,url是ajax的提交地址,type是post方式的,data就直接通过form进行数据的序列化,而不需要像以前那样一个个的去查找,实在是方便不少。
下面是后台接收ajax数据的java代码
@RequestMapping(value = "/add",produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity<?> add(Cart cart){ if(cart.getItems().size()>0){ shopCartService.save(cart); } return new ResponseEntity<Cart>(cart, HttpStatus.OK); }
标签:ajax
原文地址:http://blog.csdn.net/fanxl10/article/details/45339839