magento2 - 在产品页面 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 代码?
解决方案
推荐阅读
- java - 如何使 ExampleMatcher 与属性不匹配?
- ios - 在 iOS 13 上拖动时,UICollectionView 单元格捕捉到原始位置
- google-cloud-platform - Dataflow REST API 的“projects.locations.templates.create”和“projects.locations.templates.launch”有什么区别?
- c# - 在 Visual Studio Development 中上传文件时有效,但在网站发布时无效
- c# - C# Azure:如何从 Microsoft.Azure.ServiceBus.Message 读取正文?
- django - mysqlclient在mac os上的python3中安装
- jestjs - NestJs 请求和响应拦截器单元测试
- python - UTF8 中的 Python 字符串 '\x80' 占用多少字节?
- android - 带有cloud_firestore,firebase_messaging的Flutter应用程序在ios中不起作用
- azure-devops - 添加环境时仍然无法选择“虚拟机”作为资源,但根据 sprint 162 发行说明它应该可用