SpringMvc后台程序:
/**
* 根据ids查找商品
*/
@RequestMapping(value = "/cartItems", method = RequestMethod.GET,produces = "application/json; charset=utf-8")
public @ResponseBody
String cartItems() {
JSONObject json = new JSONObject();
List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
Cart cart = cartService.getCurrent();
if(cart != null)
{
Set<CartItem> alls = cart.getCartItems();
Iterator<CartItem> iter = alls.iterator();
while(iter.hasNext())
{
HashMap<String,Object> hm = new HashMap<String,Object>(); //最外层,父节点
CartItem ci = iter.next();
hm.put("id", ci.getId());//id属性 ,数据传递
hm.put("name", ci.getProduct().getName()); //name属性,显示节点名称
hm.put("image",ci.getProduct().getThumbnail()==null?"":ci.getProduct().getThumbnail());
hm.put("count", ci.getQuantity());
hm.put("price", ci.getProduct().getPrice());
list.add(hm);
}
}
JSONArray arr = new JSONArray(list);
try {
json.put("success", true);
json.put("arr", arr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arr.toString();
}
前台代码:
//取得购物车项
$.ajax({
url: "${base}/cart/cartItems.jhtml",
type: "GET",
dataType: "json",
traditional: true,
cache: false,
success: function(data) {
var msg = eval(data);
$.each(msg, function (index, item) {
//循环获取数据
var id = msg[index].id;
var name = msg[index].name;
var image = msg[index].image;
var count = msg[index].count;
var price = msg[index].price;
[@compress single_line = true]
var html =
'<dt><a href="#"><img src="${base}'+image+'"<\/a><\/dt><dd><p>'+name+'<\/p><h1>¥'+price+'<span>×'+count+'<\/span><a href="#">删除<\/a><\/h1><\/dd>';
[/@compress]
$("#cartItems").append(html);
});
}
});