This is how my AJAX script looks like:
<script>
function addToCart(itemId) {
var url = "./addToCart/" + itemId;
$.get(url, function(response){
$('#shoppingCartId').text(response);
});
}
</script>
It gets an itemId from the JSP, calls the controller method below with this itemId. This is the controller method:
@RequestMapping(value="/addToCart/{itemId}", method=RequestMethod.GET)
public @ResponseBody ShoppingCart addToCart(@PathVariable Long itemId, @ModelAttribute ShoppingCart shoppingCart) {
Item item = itemService.getItemWithId(itemId);
if(item != null) {
shoppingCartService.addItem(shoppingCart, item);
}
return shoppingCart;
}
The question is, I would like to place the response (Shopping Cart Object) into this table, which is on the same jsp. But How?:
<div class="span2" id="shoppingCartId">
<table class="table table-condensed">
<tr>
<td><b>#</b></td>
<td><b>NAME</b></td>
<td><b>PRICE</b></td>
</tr>
<c:forEach items="${shoppingCart.items}" var="item" varStatus="count">
<tr>
<td>${count}</td>
<td>${item.name}</td>
<td>${item.price}</td>
</tr>
</c:forEach>
<tr>
<td></td>
<td></td>
<td><b>Total Price: {shoppingCart.totalPrice}</b></td>
</tr>
</table>
</div>
If i could add the response into the request attributes, the table will be fulfilled. But how can i place this object into the request? or into the table actually?
I think the problem is here, in the success function:
function(response){
$('#shoppingCartId').text(response);
}
Here i get the shoppingCartId DOM object (which is the division where the table is), and set the response object (which is the shoppingCart) as Text. I can even set the attributes of shoppingCart object like this:
function(response){
$('#shoppingCartId').text(response.totalPrice);
}
And totalPrice of the object will be displayed on the jsp where the table is seen. But how to place this response object directly to the table? As i have already said, if i could add the response into the request attributes like any other java object, the table will be fulfilled. But how can i place this JSON object into the request? or into the table actually?