【问题标题】:Value not refreshing after second ajax call第二次ajax调用后值不刷新
【发布时间】:2017-08-26 04:00:24
【问题描述】:

我正在做一个 ajax 调用并使用 jQuery 渲染一个购物车。

function show_cart() {

    $.ajax({
        url: 'functions/show-cart.php',
        type: 'POST',
        dataType: 'json',
    })

    .done(function (data) {
        $.each(data.cart, function (index, item) {

            var showCart = `

                <div class="row hr marg-b-30 marg-t-30">
                        <div class="col-md-2 col-sm-2 col-xs-12 marg-b-30">
                            <img src="uploads/${item.pic_name}" alt="${item.product_name}" class="">
                        </div>
                        <div class="col-md-5 col-sm-5 col-xs-12 marg-b-30">
                            <a href="#" class=""><b>Product</b></a><b class="right">R${item.price}</b>
                            <p class="">${item.product_name}</p>
                            <button class="btn btn-xs bg-color--second removeItem" data-id="${item.item_id}" data-itr="${item.i}">Remove <i class="material-icons">delete</i></button>

                        </div>
                        <div class="col-md-3 col-sm-3 col-xs-12 marg-b-30">
                            <div class="input input-counter">
                                <div class="input__helper pos-left pointer input-counter__plus cartPlus" data-itr="{$i}">
                                    <i class="material-icons ico-xs"></i>
                                </div>
                                <input type="text" class="text-center" readonly="" value="${item.each_item}">
                                <div class="input__helper pointer input-counter__minus">
                                    <i class="material-icons ico-xs"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2 col-sm-2 col-xs-12 marg-b-30 text-right text-left-xs">
                            <span class="price-xs">R${item.subtotal}</span>
                        </div>
                    </div>`;

            $(".somediv").append(showCart);


        });

        $("#total").append(data.total);
        $("#subtotal").append(data.total);


    })

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

购物车中的每个商品都有一个删除/删除按钮,当用户单击该按钮时,它会调用我的删除函数,从购物车中删除该商品(淡出)。然后,我对最初显示购物车的相同 show-cart.php 脚本进行 ajax 调用,希望这将更新小计和总值,但它们与删除购物车项目之前保持相同。我怎样才能让总数更新?

这里是删除商品或从购物车中移除功能:

function remove_item() {

    $("body").on("click", ".removeItem", function () {
        var id = $(this).data('id');
        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();
            $( "#total" ).html(data.total);//This gives me the same total as before I removed the item

        })

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

show-cart.php

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

    $itemsInCart = 0;

} else {

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

            $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,
                    "subtotal" => $subtotal,
                    "item_id" =>$item_id,
                    "i" => $i

                    );

                    $i++;
                }
            }

            $stmt->close();
        }



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


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"]);
            sort($_SESSION['cart_array']);
        }
    }

【问题讨论】:

  • 你从哪里得到这个返回show-cart.phpdata?来自数据库?
  • 是的,产品 ID 用于从数据库中获取其余产品信息。
  • 你在 ajax done 回调中试过console.log(data.total) 吗?它改变了吗?
  • 如果我 console.log 退出,data.total 与我从购物车中删除该项目之前完全相同,即:与我第一次加载购物车时相同。如果我删除第二项,则总数会更改为删除第一项后的应有值。
  • 谢谢。我只是试过了,没有区别。 $.ajax({ cache: false, url: 'functions/show-cart.php', type: 'POST', dataType: 'json', data: { indexToRemove: indexToRemove },

标签: jquery ajax


【解决方案1】:

您应该在返回 ajax 响应之前取消设置会话中的项目。试试这个:

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"]);
                sort($_SESSION['cart_array']);
            }
        }    

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

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

    } else {

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

                $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,
                        "subtotal" => $subtotal,
                        "item_id" =>$item_id,
                        "i" => $i

                        );

                        $i++;
                    }
                }

                $stmt->close();
            }



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

【讨论】:

  • 啊哈,现在我们到了某个地方。如果我的购物车中只有 2 件商品,这将非常有效。一旦我有 3 个并删除最后一个,就会出现严重错误,在控制台中它会显示倒数第二个项目的总数。
  • 尝试注释掉这一行sort($_SESSION['cart_array']);
  • 是 sort() 函数让我很困惑。我删除了,一切都很好
  • 最后一件事。当我从购物车中删除所有物品时,我收到一个错误,但这并不是一个真正有用的描述。我试过这个,但它不能解决我的问题。 if(data.total &lt; 1) { alert("cart empty"); } else { $( "#total" ).html(data.total); }
  • 错误只是说 parsererror: SyntaxError: Unexpected end of JSON input。这是在控制台中
猜你喜欢
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 2019-01-27
  • 1970-01-01
相关资源
最近更新 更多