【问题标题】:Remove an item from the server with JSON [duplicate]使用 JSON 从服务器中删除项目 [重复]
【发布时间】:2015-03-21 18:02:34
【问题描述】:

我真的很感谢这里的一些帮助。我的JSON知识有限,解决不了。

我需要从我通过 JSON 创建的购物车快速视图中删除一个项目。前端似乎可以工作,但它不能,因为它没有从 JSON 对象中删除项目。

JSON 对象的样子。

[
    {
        "id": 216687,
        "productId": 9604505,
        "catalogId": 306758,
        "name": "xxxxxxxxx1",
        "description": "",
        "quantity": 1,
        "totalPrice": "38,00",
        "smallImage": "/images/products/large/xxxxx.jpg",
    },
    {
        "id": 216687,
        "productId": 9604503,
        "catalogId": 306756,
        "name": "xxxxxxxxx1",
        "description": "",
        "quantity": 1,
        "totalPrice": "38,00",
        "smallImage": "/images/products/large/xxxxx.jpg",
    }
]

jQuery 函数:

//Deleting Items
$(document).on('click', '.shopping-cart .delete i', function(){
    var $target = $(this).parent().parent();
    var $positions = $('.shopping-cart .item');
    $target.hide(300, function(){
        $.when($target.remove()).then( function(){
            if($positions.length === 1) {
                $('.shopping-cart .items-list').remove();
                $('.shopping-cart .title').text('Shopping cart is empty!');
            }
        });
    });
});

我认为我没有正确删除该项目。

【问题讨论】:

  • Json 是否存储在某个变量中?
  • 你用 JSON 做什么?在页面上呈现一些内容?更新服务器?目前尚不清楚您的jquery代码和json之间的关系是什么。
  • @Mike 我对 json 很不好,我用 this.items 获取对象,因为 globals.items 返回 null。
  • @technophobia,在页面上呈现内容,但我也需要它来在删除项目时修改服务器中的内容
  • @jogesh_pi 这是我发现的第一篇文章没有多大帮助

标签: jquery json


【解决方案1】:

我看不到您甚至试图从数组中删除该项目的位置。我的 jQuery 有点生疏,但我只看到 DOM 操作正在进行。

您必须在列表中找到该项目并将其删除。

   // code elsewhere
    var id = 216687;

    RemoveItem(id);

    // function to remove item
    function RemoveItem(id) {    
        for(var i = 0; i < data.length; i++) {
            // don't know what your criteria for removal is, but you can match any property
            if (data[i].id == id) {
                // removes the element when the match is found based on your criteria for removal
                var smallerArray = data.splice(i, 1);
            }
        }
    }

【讨论】:

  • 嗨,谢谢,我删除了 json 尝试,因为一切都很混乱。所以你对这段代码是对的,我什至没有试图删除任何东西。所以我需要获取项目的ID?并从对象中删除该 ID?
  • @TyraPululi 这是一个我无法为你回答的设计决定。您可以使用 id、productId 等。这取决于您。无论你想使用什么,你都必须在 DOM 中的某个地方可以访问。如果 id 都是唯一的,您可以将这些 id 设置为代表购物车中商品的 id 元素,然后以这种方式获取 id。类似RemoveItem($cartItem.attr('id'));
  • 我还在想办法
猜你喜欢
  • 2016-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-04
  • 2013-09-17
  • 1970-01-01
  • 2013-06-09
  • 2016-01-05
相关资源
最近更新 更多