通过在购物车页面中使用AJAX添加数量更新选项,有助于改善Magento 2网站的用户体验。
按照以下简单步骤在Magento 2中创建新扩展,来添加AJAX功能以更新购物车页面中的商品数量。
步骤1:
在以下文件路径中创建一个名为registration.php的新php文件,
文件路径:app/code/Alwayly/AutoUpdateCartItemQty/registration.php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Alwayly_AutoUpdateCartItemQty',
__DIR__
);
第2步:
在以下文件路径中创建名为module.xml的xml文件以定义新模块,
文件路径:app/code/Alwayly/AutoUpdateCartItemQty/etc/module.xml
在这里,我们必须指定我们的自定义模块的名称,如Alwayly_AutoUpdateCartItemQty和它的安装版本如下,
第3步:
在以下文件路径中创建名为checkout_cart_index.xml的xml文件,
文件路径:app/code/Alwayly/AutoUpdateCartItemQty/view/frontend/layout/checkout_cart_index.xml
在此文件中,我们必须指定自定义模块的模板文件,如下所示,
第4步:
在以下文件路径中创建名为script.phtml的phtml文件,
文件路径:app/code/Alwayly/AutoUpdateCartItemQty/view/frontend/templates/script.phtml
以下是script.phtml文件的代码,该文件将用于在结帐页面加载我们的自定义模块js文件,
require ([
'jquery'
],
function ($) {
$(window).on("load", function () {
require([
'Alwayly_AutoUpdateCartItemQty/js/cartItemQtyUpdate'
]);
});
});
第5步:
最后,在以下文件路径中创建名为cartItemQtyUpdate.js的JS文件,
文件路径:app/code/Alwayly/AutoUpdateCartItemQty/view/frontend/web/js/cartItemQtyUpdate.js
在此文件中,我们必须添加以下代码,用于在更改qty字段值时使用ajax更新购物车的商品数量,
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);
/* This is for reloading the minicart */
customerData.reload(sections, true);
/* This is for reloading the totals summary */
var deferred = $.Deferred();
getTotalsAction([], deferred);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
}
});
});
});
});
完成上述步骤后,在Magento 2安装的根目录下运行以下SSH命令,
php bin/magento setup:upgrade
然后,清除所有Magento缓存并检查购物车页面中的数量更新选项。
Note:我们已经使用Luma主题在Magento 2.3上测试了上述代码。