У меня есть код для обновления количества в корзине с помощью запроса fetch () , и я немного изменил его:
updateMainItem(line, quantity, name, variantId) {
const body = JSON.stringify({
line,
quantity,
sections: this.getSectionsToRender().map((section) => section.section),
sections_url: window.location.pathname,
});
fetch(`${routes.cart_change_url}`, { ...fetchConfig(), ...{ body } })
.then((response) => {
return response.text();
})
.then((state) => {
const parsedState = JSON.parse(state);
const quantityElement =
document.getElementById(`Quantity-${line}`) || document.getElementById(`Drawer-quantity-${line}`);
const items = document.querySelectorAll('.cart-item');
const itemsNeedingVouchers = parsedState.items.filter(i => i.properties?.Vouchers === 'Yes');
const vouchers = parsedState.items.filter(i => i.variant_id === 46396120596724);
if (itemsNeedingVouchers && vouchers) {
const updateVoucher = async (id, quantity) => {
await fetch('/cart/update.js', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ updates: { [id]: quantity } })
}).then((response) => {
return response.text();
}).then((responseText) => {
})
}
for (const item of itemsNeedingVouchers) {
const voucher = vouchers.find(v => v.properties?.['For Variant'] === String(item.id));
if (voucher) {
updateVoucher(voucher.id, item.quantity)
} else {
updateVoucher(voucher.id, 0)
}
}
}
if (parsedState.errors) {
quantityElement.value = quantityElement.getAttribute('value');
this.updateLiveRegions(line, parsedState.errors);
return;
}
this.classList.toggle('is-empty', parsedState.item_count === 0);
const cartDrawerWrapper = document.querySelector('cart-drawer');
const cartFooter = document.getElementById('main-cart-footer');
if (cartFooter) cartFooter.classList.toggle('is-empty', parsedState.item_count === 0);
if (cartDrawerWrapper) cartDrawerWrapper.classList.toggle('is-empty', parsedState.item_count === 0);
this.getSectionsToRender().forEach((section) => {
const elementToReplace =
document.getElementById(section.id).querySelector(section.selector) || document.getElementById(section.id);
elementToReplace.innerHTML = this.getSectionInnerHTML(
parsedState.sections[section.section],
section.selector
);
});
const updatedValue = parsedState.items[line - 1] ? parsedState.items[line - 1].quantity : undefined;
let message = '';
if (items.length === parsedState.items.length && updatedValue !== parseInt(quantityElement.value)) {
if (typeof updatedValue === 'undefined') {
message = window.cartStrings.error;
} else {
message = window.cartStrings.quantityError.replace('[quantity]', updatedValue);
}
}
this.updateLiveRegions(line, message);
const lineItem =
document.getElementById(`CartItem-${line}`) || document.getElementById(`CartDrawer-Item-${line}`);
if (lineItem && lineItem.querySelector(`[name="${name}"]`)) {
cartDrawerWrapper
? trapFocus(cartDrawerWrapper, lineItem.querySelector(`[name="${name}"]`))
: lineItem.querySelector(`[name="${name}"]`).focus();
} else if (parsedState.item_count === 0 && cartDrawerWrapper) {
trapFocus(cartDrawerWrapper.querySelector('.drawer__inner-empty'), cartDrawerWrapper.querySelector('a'));
} else if (document.querySelector('.cart-item') && cartDrawerWrapper) {
trapFocus(cartDrawerWrapper, document.querySelector('.cart-item__name'));
}
publish(PUB_SUB_EVENTS.cartUpdate, { source: 'cart-items', cartData: parsedState, variantId: variantId });
})
.catch(() => {
this.querySelectorAll('.loading__spinner').forEach((overlay) => overlay.classList.add('hidden'));
const errors = document.getElementById('cart-errors') || document.getElementById('CartDrawer-CartErrors');
errors.textContent = window.cartStrings.error;
})
.finally(() => {
this.disableLoading(line);
});
}
< /code>
мои редактирования: < /p>
const itemsNeedingVouchers = parsedState.items.filter((i) => i.properties?.Vouchers === "Yes");
const vouchers = parsedState.items.filter((i) => i.variant_id === 46396120596724);
if (itemsNeedingVouchers && vouchers) {
const updateVoucher = async (id, quantity) => {
await fetch("/cart/update.js", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ updates: { [id]: quantity } }),
})
.then((response) => {
return response.text();
})
.then((responseText) => {});
};
for (const item of itemsNeedingVouchers) {
const voucher = vouchers.find((v) => v.properties?.["For Variant"] === String(item.id));
if (voucher) {
updateVoucher(voucher.id, item.quantity);
} else {
updateVoucher(voucher.id, 0);
}
}
}
< /code>
И это работает хорошо! Но с количеством и ценой продукта ваучера Cart не обновляется сразу после запроса. Но только после повторяющегося запроса. То есть, как будто я был на 1 шаг поздно.
Как это исправить?
Подробнее здесь: https://stackoverflow.com/questions/797 ... ch-request
Обновление тележки с помощью запроса Fetch ⇐ Javascript
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Обновление автоматического триггера об изменении количества на странице тележки WooCommerce
Anonymous » » в форуме Php - 0 Ответы
- 3 Просмотры
-
Последнее сообщение Anonymous
-