因为这个问题困扰了我好久,所以把解决的方案跟大家分享一下,就是在ajax成功返回执行的方法中给隐藏表单中的对应id赋值就好了,就是下面这个图中框起来的部分
JS代码
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#detail_num").blur(function() {
var count = $("#detail_num").val();//获取的text框中的值
// request.setAttribute("amount",count);
// 使用ajax发送请求
$.ajax({
url: "/TotalPriceServlet", // 要访问的地址,这里访问的是servlet映射地址
cache: false, // 是否缓存
data: {"count":count,
"price":${requestScope.price},
}, // 相当于地址栏后面的参数
success: function(result){ // 访问成功后,执行的方法,参数是后台的结果
// 将获取到的数据写入span标签
$("#sum").text(result);
$("#count").val(count);//将数量重新写入隐藏表单的值中
}
})
});
})
html代码
使用隐藏表单来实现数据的上传
<input type="text" id="detail_num" class="num_show fl" value="1">
<a id="a" href="javascript:document:formId.submit('formId');" class="add_cart" id="add_cart">加入购物车</a>
<form id="formId" action="/AddCartServlet" method="post">
<input type="hidden" value=${requestScope.url} name="url">
<input type="hidden" value=${requestScope.name} name="name">
<input type="hidden" value=${requestScope.price} name="price">
<input type="hidden" value=${requestScope.specification} name="specification">
<input type="hidden" id="count" value="1" name="count">
<input type="hidden" value=${sessionScope.userId} name="userId">
</form>
servlet后台
public class AddCartServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String url = req.getParameter("url");
String name = req.getParameter("name");
String price = req.getParameter("price");
String specification = req.getParameter("specification");
String count = req.getParameter("count");
String userId = req.getParameter("userId");
System.out.println(url);
System.out.println(name);
System.out.println(price);
System.out.println(specification);
System.out.println(count);
System.out.println(userId);
UserServiceImpl userService = new UserServiceImpl();
UserDao userDao = new UserDaoImpl();
userService.setUserDao(userDao);
ShoppCart shoppCart=new ShoppCart(url,name,Double.valueOf(price),specification,Integer.valueOf(count),Integer.valueOf(userId));
int i = userService.addShoppCart(shoppCart);
List<ShoppCart> shoppCarts = userService.queryShoppCart(Integer.valueOf(userId));
req.getSession().setAttribute("shoppCarts",shoppCarts);
resp.sendRedirect("cart.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
throws ServletException, IOException { doGet(req, resp); } }
|