【问题标题】:item will not remove from cart商品不会从购物车中移除
【发布时间】:2017-09-02 20:05:17
【问题描述】:

我没有使用产品 ID,而是为购物车中的每个商品设置了一个索引,从 0 开始。购物车中的每个商品都有自己的从购物车中删除/删除按钮。单击该按钮时,该值通过 ajax 发布到 php 脚本:

if(isset($_POST['indexToRemove']) && $_POST['indexToRemove'] !== "") {

        $key_to_remove = $_POST['indexToRemove'];
        if(count($_SESSION['cart_array']) <=1) {
            unset($_SESSION['cart_array']);

        } else {

            unset($_SESSION['cart_array'][$key_to_remove]);

        }
    }

如果我单击时 console.log() indexToRemove,它会在控制台中显示正确的值。但是,该项目永远不会从会话中删除,并且控制台中没有错误来帮助进行故障排除。

这里是 jQuery:

$("body").on("click", ".removeItem", function () {
        var indexToRemove = $(this).data('itr');
        var div = $(this).parents("div.hr");
        $.ajax({
            url: 'functions/show-cart.php',
            type: 'POST',
            dataType: 'json',
            data: {
                indexToRemove: indexToRemove
            },
            beforeSend: function () {
                $(div).html("<img src='images/spinner.gif'>");
                $("#total").empty();
            },
        })

        .done(function (data) {
            $(div).fadeOut();
            show_cart();
        })

        .fail(function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus + ': ' + errorThrown);
            console.warn(jqXHR.responseText);
        })
    })

加入购物车代码:

$quantity = 1;
$product_id = $_POST['id'];
$colour = $_POST['colour'];
$size = $_POST['size'];


   $key = "{$product_id}.{$colour}.{$size}";
   if (empty($_SESSION['cart_array'][$key])) {
     $_SESSION['cart_array'][$key] = array(
        "item_id" => $product_id,
        "quantity" => $quantity,
        "colour" => $colour,
        "size" => $size,
     );
   }
   else {
      $_SESSION['cart_array'][$key]['quantity'] += $quantity;
   }

显示购物车物品的php代码:

if(!isset($_SESSION['cart_array'])) {

    $itemsInCart = 0;
    $response['total'] = 0;
    echo json_encode($response);

} else {

        $featured = "Yes";
        $i=0;
        foreach($_SESSION['cart_array'] as $each_item) {
            $item_id = $each_item['item_id'];
            $colour = $each_item['colour'];
            $size = $each_item['size'];


        $stmt = $link->prepare("SELECT `product_name`, `price`, `pic_name` FROM `products` as `p` INNER JOIN `product_images` as `pi` ON p.`id` = pi.`product_id` WHERE p.`id` = ? AND `featured` = ?");
            $stmt->bind_param("is", $item_id, $featured);
            $stmt->execute();
            $result = $stmt->get_result();
            $numRows = $result->num_rows;
            if($numRows > 0) {
                while($row = $result->fetch_assoc()) {
                    $product_name = sanitize($row['product_name']);
                    $price = sanitize(money_format('%.2n', $row['price']));
                    $subtotal = money_format('%.2n', $each_item['quantity'] * $price);
                    $pic_name = $row['pic_name'];
                    $cartTotal = $subtotal + $cartTotal;
                    $quantity = $each_item['quantity'];

                    $cart_details[] = array(

                    "product_name" => $product_name,
                    "price" => $price,
                    "subtotal" => $subtotal,
                    "pic_name" => $pic_name,
                    "each_item" => $quantity,
                    "item_id" =>$item_id,
                    "i" => $i,
                    "colour" => $colour,
                    "size" => $size,


                    );

                    $i++;
                }
            }

            $stmt->close();
        }


    $response['total'] = $cartTotal;
    $response['cart'] = $cart_details;
    echo json_encode($response);
}

【问题讨论】:

    标签: php jquery ajax


    【解决方案1】:

    在您的客户端,您需要更改此行:

    data: {
         indexToRemove: indexToRemove
     },
    

    到:

    data: JSON.stringify({indexToRemove: indexToRemove}),
    

    而在服务器端,第一个问题是:

    unset($_SESSION['cart_array']["$key_to_remove"]);
                                  ^              ^
    

    改成:

    unset($_SESSION['cart_array'][$key_to_remove]);
    

    第二个是(因为item是json对象你需要json_decode):

    $key_to_remove = $_POST['indexToRemove'];
    

    改成:

    $key_to_remove = json_decode($_POST['indexToRemove']);
    

    【讨论】:

    • 如果我只有 1 个项目,那么它可以工作并且该项目被删除
    • 我不知道如何检查您的要求。如果我 console.log() out the indexToRemove,第一个购物车项目的值为 0,降神会项目的值为 1,第三个项目的值为 2,依此类推
    • @user8463989 抱歉,您能否将 $key_to_remove 的值转储到 PHP 中,并为您的数组转储相同的值并测试密钥是否有效?原因是我看到 $key = "{$product_id}.{$colour}.{$size}"; 我认为这不是一个数字。
    • @user8463989 您是否考虑过使用 array_push 和 array_search 来向数组中插入一个新元素并获取值而不是像您一样创建索引?
    猜你喜欢
    • 2018-07-22
    • 2015-07-05
    • 1970-01-01
    • 2018-10-19
    • 2013-10-17
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多