Magento 2 - 在ajax更改数量后重新加载总计

Ant*_*ony 5 php ajax jquery knockout.js magento2

我想使用ajax来更改购物车magento 2购物车页面上的一个商品的数量.

我添加了这个javascript:

$('.cart.item .qty').on({
    change: function() {
        var post_url = $(this).attr('data-post-url');

        $.post(post_url, $(this).serialize(), function(data) {
            $(".form-cart").replaceWith(data.cart_html);
            $("#cart-totals").replaceWith(data.totals_html);
            $("#cart-totals").trigger('contentUpdated');
        }, "json");
    }
});
Run Code Online (Sandbox Code Playgroud)

data.totals_html的值是

<div id="cart-totals" class="cart-totals" data-bind="scope:'block-totals'">
<!-- ko template: getTemplate() --><!-- /ko -->
<script type="text/x-magento-init">
        {
            "#cart-totals": {
                "Magento_Ui/js/core/app": {"components":{"block-totals":....}
</script>
Run Code Online (Sandbox Code Playgroud)

当我更改数量时,总组件内容不刷新..

任何人都有想法在更换html代码后动态更新总组件?

小智 1

您可以参考以下方法来ajax重新加载购物车中的块总数:

define([
    "jquery",
    'Magento_Checkout/js/action/get-payment-information',
    'Magento_Checkout/js/model/totals'
], function($, getPaymentInformationAction, totals) {
    $('.cart.item .qty').on({
        change: function() {
            var post_url = $(this).attr('data-post-url');
            $.post(post_url, $(this).serialize(), function(data) {
                //custom your update
                $(".form-cart").replaceWith(data.cart_html);
                $("#cart-totals").replaceWith(data.totals_html);
                //reload block total
                var deferred = $.Deferred();
                totals.isLoading(true);
                getPaymentInformationAction(deferred);
                $.when(deferred).done(function() {
                    totals.isLoading(false);
                });
                //end
            }, "json");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)