我正在尝试将响应从控制器传递给ajax。事实是,每次删除购物篮中的产品时,我都想更新总数,我尝试通过以下方式进行操作,但是它会打印出cart.jsp的所有html代码。
CartControler.java
package controller;
import dao.ProductDao;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Item;
import model.pojo.Products;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class CartController {
ModelAndView mav = new ModelAndView();
@RequestMapping("/cart")
public ModelAndView cart() {
mav.setViewName("cart");
return mav;
}
@RequestMapping(value="/deleteItem")
public String deleteItem(HttpServletRequest request, HttpServletResponse response) throws IOException {
ProductDao prodDao = new ProductDao();
int prodId = Integer.parseInt(request.getParameter("prodId"));
HttpSession session = request.getSession(true);
ArrayList<Item> items = session.getAttribute("cart") == null ? null : (ArrayList) session.getAttribute("cart");
if(items != null) {
for(Item i : items) {
if(i.getProdId() == prodId) {
items.remove(i);
break;
}
}
}
double total = 0;
for(Item i : items) {
Products product = prodDao.getProduct(i.getProdId());
total += i.getQuantity() * product.getPrice();
}
response.getWriter().print(Math.round(total * 100.0) / 100.0);
return "redirect:/cart";
}
}
cart.js
$(function() {
$('tr #deleteItem').click(function(event) {
event.preventDefault();
var element = $(this);
var prodId = element.parent().find('#itemId').text();
$.ajax({
url: 'deleteItem',
type: 'post',
data: {prodId : prodId},
success: function(r){
element.parent().parent().remove();
var elementstable = $('#shop-table tr');
if(elementstable.length <= 1) {
$('#cart-container').append("<h4>THERE ARE CURRENTLY NO ITEMS IN YOUR BASKET.</h4>");
}
$('#txt-total').text(r);
}
});
});
});
我不知道出什么问题了,为什么不打印页面的所有html代码而不是全部。