2013-10-17 79 views
1

我正在使用jQuery來更新購物車,然後用json對象返回想通過此循環並顯示'新'更新購物車上的頁。使用jQuery與jQuery在頁面上顯示購物車(沒有頁面刷新)

我的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

什麼是json和html結構? – lolol

+0

你可以發佈JSON示例嗎? – tborychowski

回答

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 
}); 
+0

+1 - 會給你一個鏡頭:) – Zabs

+0

@Zabs我稍微更新它以匹配你的json格式 – tborychowski

+1

你對於大寫字母A真棒! :) – Zabs