我正在使用jQuery更新购物车,然后使用它返回的json对象循环浏览并在页面上显示“新的”更新购物车。
我的ajax函数在下面 - 这会返回一个json对象,但有点不确定如何将其恢复到视图中
function updateCart( qty, rowid ){
$.ajax({
type: "POST",
url: "/cart/ajax_add_item",
data: { rowid: rowid, qty: qty },
success: function(data){
// use this data and re-display on the page
}
});
}
使用jQuery将此内容显示回页面的最佳方法是什么?
//更新 - 示例json结构
{
"722fc276f5b5f44bdad431d89c95019f": {
"rowid": "722fc276f5b5f44bdad431d89c95019f",
"id": "4",
"qty": "2",
"price": "255.00",
"name": "Apple iPhone 4S",
"options": {
"condition": "Working",
"merchant": "BBW",
"attributes": "16GB, Any"
},
"custom": {
"merchant_url": "http:\/\/www.buybackworld.com",
"url": "bbw\/sell-apple-iphone-4s-16gb-at-t-a1387\/10018.html",
"image": "\/assets\/images\/devices\/iphone-4s.jpg",
"merchant_id": "63",
"merchant": "bbw",
"device_id": "354"
},
"subtotal": 510
}
}
答案 0 :(得分:1)
您需要某种渲染功能,例如
var render = function (json) {
var _html = '<div class="cart">';
if (json) {
$.each(json, function (i, item) { // loop through the json data
_html += '- ' + item.name + ' (' + item.price + ')';
})
}
_html += '</div>';
$('#myCartContainer').html(_html); // replace container with new cart data
};
$.ajax({
type: "POST",
url: "/cart/ajax_add_item",
data: { rowid: rowid, qty: qty },
success: render // "render" when data received
});