首页 > 解决方案 > 在产品页面 magento 2 上获取选定的产品库存数量

问题描述

我是magento 2的新手

我想使用 ajax 获取选定的产品库存数量。我可以通过在 app/design/frontend/Sm/market/Magento_Catalog/templates/product/view/addtocart.phtml文件中使用以下脚本来获取选定的产品 ID

var $ = jQuery.noConflict();
$(window).load(function() {
    requirejs(['jquery'], function(jQuery) {
        var selected_options = {};
        jQuery('.swatch-attribute').each(function(k, v) {
            var attribute_id = jQuery(v).attr('attribute-id');
            var option_selected = jQuery(v).attr('option-selected');
            if (!attribute_id || !option_selected) {
                return;
            }
            selected_options[attribute_id] = option_selected;
        });
        var product_id_index = jQuery('[data-role=swatch-options]').data('mageSwatchRenderer').options.jsonConfig.index;
        var found_ids = 0;
        jQuery.each(product_id_index, function(product_id, attributes) {
            var productIsSelected = function(attributes, selected_options) {
                return _.isEqual(attributes, selected_options);
            }
            if (productIsSelected(attributes, selected_options)) {
                found_ids += parseInt(product_id);
            }
        });
        console.log(found_ids);
        alert(found_ids);
    });
});

并且还可以使用此代码计算产品数量

$product_Id = 1748;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$stockInfo = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface')->getStockItem($product_Id);
$stockqty = (int)$stockInfo->getQty();
echo $stockqty;

但是如何动态地将 product_id 传递给 php 代码?

标签: magento2productcatalog

解决方案


推荐阅读