【问题标题】:Using json with jQuery to display cart on the page (without a page refresh)使用 json 和 jQuery 在页面上显示购物车(无需页面刷新)
【发布时间】:2013-10-17 23:06:20
【问题描述】:

我正在使用 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
    }
}

【问题讨论】:

  • 什么是json和html结构?
  • 你能发布一个 JSON 样本吗?

标签: jquery ajax json


【解决方案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
});

【讨论】:

  • 你的大写字母A太棒了! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-05
  • 2016-03-30
  • 1970-01-01
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多