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

时间:2016-10-12 15:51:02

标签: php jquery ajax 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");
    }
});

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>

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

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

4 个答案:

答案 0 :(得分:3)

ajax更改数量后重新加载总购物车

  1. 步骤

在您的自定义中,他们创建(Magento_Theme / layout / checkout_cart_index.xml)

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceContainer name="content">
        <block class="Magento\Framework\View\Element\Template" name="cart.ajax.qty.update"  template="Magento_Theme::js.phtml" after="-"/>
    </referenceContainer>
</body>

2。步骤

创建js.phtml文件(Magento_Theme / templates / js.phtml)

<script>
require ([
        'jquery',
    ],
    function ($) {
       $(window).on("load", function () {
            require([
                'custom'
            ]);
        });
    });

3.步骤 在主题Web文件夹(Namespace / Yourtheme / web / js / custom.js)中创建custom.js文件

    define([
    'jquery',
    'Magento_Checkout/js/action/get-totals',
    'Magento_Customer/js/customer-data'
     ], function ($, getTotalsAction, customerData) {

    $(document).ready(function(){
    $(document).on('change', 'input[name$="[qty]"]', function(){
        var form = $('form#form-validate');
        $.ajax({
            url: form.attr('action'),
            data: form.serialize(),
            showLoader: true,
            success: function (res) {
                var parsedResponse = $.parseHTML(res);
                var result = $(parsedResponse).find("#form-validate");
                var sections = ['cart'];

                $("#form-validate").replaceWith(result);

                // The mini cart reloading
                customerData.reload(sections, true);

                // The totals summary block reloading
                var deferred = $.Deferred();
                getTotalsAction([], deferred);
            },
            error: function (xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                console.log(err.Message);
            }
        });
       });
      });
    });

4.Step(映射您的js文件)

在主题根目录(命名空间/yourtheme/requirejs-config.js)上创建requirejs-config.js

var config = {
   map: {
    '*': {
        custom:'js/custom'
    }
  }
};

现在使用ajax进行数量更新工作 如果有任何问题,请在评论中提问。

答案 1 :(得分:0)

您可以通过这种方式咨询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");
        }
    });
});

答案 2 :(得分:0)

只需运行以下js代码-

require(
[
   'Magento_Checkout/js/model/quote',
   'Magento_Checkout/js/model/cart/totals-processor/default'
],
function(
   quote,
   totalsDefaultProvider
) {
     totalsDefaultProvider.estimateTotals(quote.shippingAddress());
  }
);

有关更多信息,请参阅this article

免责声明:我是MexBS(发布本文的公司)的首席执行官

答案 3 :(得分:0)

将cartQtyUpdate.js中的代码更改为此代码

define([
'jquery',
'Magento_Checkout/js/action/get-totals',
'Magento_Customer/js/customer-data'
], function ($, getTotalsAction, customerData) {

$(document).ready(function(){
    $(document).on('change', 'input[name$="[qty]"]', function(){
        var form = $('form#form-validate');
        $.ajax({
            url: form.attr('action'),
            data: form.serialize(),
            showLoader: true,
            success: function (res) {
                var parsedResponse = $.parseHTML(res);
                var result = $(parsedResponse).find("#form-validate");
                var sections = ['cart'];

                $("#form-validate").replaceWith(result);

                /* Minicart reloading */
                customerData.reload(sections, true);

                /* Totals summary reloading */
                var deferred = $.Deferred();
                getTotalsAction([], deferred);
            },
            error: function (xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                console.log(err.Message);
            }
        });
    });
    $(document).on('click', '.alo_qty', function() {
        var form = $('form#form-validate');
        $.ajax({
            url: form.attr('action'),
            data: form.serialize(),
            showLoader: true,
            success: function (res) {
                var parsedResponse = $.parseHTML(res);
                var result = $(parsedResponse).find("#form-validate");
                var sections = ['cart'];

                $("#form-validate").replaceWith(result);

                /* Minicart reloading */
                customerData.reload(sections, true);

                /* Totals summary reloading */
                var deferred = $.Deferred();
                getTotalsAction([], deferred);
            },
            error: function (xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                console.log(err.Message);
            }
        });
    });
});
});

现在效果很好