![](/img/trans.png)
[英]Shopify Ajax API, Alpine JS, add user selected options to cart using Ajax
[英]Shopify, Liquid, Alpine JS, Ajax can't redirect to cart after firing addToCart
无法弄清楚为什么在我的 ajax addToCart function 被调用后没有被重定向到购物车?
产品按预期进入购物车。
我试过 preventingDefault 而不是 preventing。
这是下图中的 response 和 formData 的样子。
这是我的产品表格。
<div class="tw-p-8">
<h2 class="tw-mb-4 tw-text-white">Your Selections</h2>
{% assign product_form_id = 'product-form-' | append: section.id %}
{%- form 'product',
product,
id: product_form_id,
class: 'form',
novalidate: 'novalidate',
data-type: 'add-to-cart-form'
-%}
<input
type="hidden"
name="id"
value="{{ product.selected_or_first_available_variant.id }}"
disabled
>
<div class="product-form__buttons">
<button
type="submit"
@click.prevent="addToCart(items, box_size)"
:class="full_box ? 'tw-bg-ctaColor' : ''"
class="tw-bg-white tw-text-brandText tw-flex tw-justify-center tw-py-4 tw-px-6 tw-rounded-full tw-font-bold"
>
<p class="" x-show="!full_box">
<span x-text="items_selected" class="tw-mr-2"></span><span class="tw-mr-2">of</span
><span class="tw-font-bold" x-text="box_size"></span><span class="tw-ml-2">Selected</span>
</p>
<p x-show="full_box" class="">Add to cart</p>
</button>
</div>
{%- endform -%}
</div>
这是我的 addToCart function。
<div
x-data="
{
addToCart(items, size){
const price = getBoxPrice(size)
console.log({price})
let itemsToAdd = items.map((item) => {
return item['title'];
})
let selectedItems = itemsToAdd.toString()
console.log({selectedItems})
console.log({itemsToAdd})
let formData = {
'items': [{
'id': 44202123100470,
'quantity': 1,
'properties': {
'Box Items': selectedItems,
}
}]
};
console.log({formData})
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
console.log(response)
return response.json();
})
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
reset()
}
}
"
class="tw-mt-12 tw-flex tw-flex-col tw-p-auto tw-bg-brandText tw-opacity-80"
> ....</div>
我解决这个问题的方法是在 Ajax 调用的成功 promise 中使用Location API添加 location.href="/cart"。
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
console.log(response)
return response.json();
})
.then((data) => {
location.href = '/cart';
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.