2013-10-17 81 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