我正在创建一种将Shopify集合中的所有产品添加到购物车中的方法,作为销售捆绑包的一种方式。
我有一个JavaScript脚本,它确定选择了哪个级别的工具包,并循环遍历集合中的每个产品。我们希望在包中添加几个产品不止一次,这些产品由标记basicbundleqty:x控制,因此代码循环遍历每个产品的标记,检查这个标签,如果它有,则qty设置为标记的后缀。
<script>
var selected = "not selected";
function kitSelect(){
selected = document.getElementById('select').value;
/*if(selected == "not selected"){
alert('Please select a kit level');
}
if(selected == "basic"){
alert('basic');
}
if(selected == "standard"){
alert('standard');
}
if(selected == "pro"){
alert('pro');
}*/
}
function addBundle(){
var qty = 0;
if(selected == "basic"){
{% for kitproduct in collections['Basic-Fixture-Plate-Starter-Kit'].products %}
qty = 1;
{% for t in kitproduct.tags %}
{% if t contains 'basicqty:' %}
{% assign qty = t | remove: 'basicqty:'%}
{% assign qty = qty | plus: 0 %}
qty = {{ qty | json }};
{% endif %}
{% endfor %}
jQuery.post('/cart/add.js', {
quantity: qty,
id: {{ kitproduct.variants[0].id }},
properties: {
}
});
alert(qty);
{% endfor %}
} else {
alert("Please select a kit level first");
}
window.location.reload(false);
}
</script>
这种方法确实有效,只有一种奇怪之处。如果没有for循环末尾的alert(qty);
行,代码就无法工作。如果不存在该警报,代码似乎只会随机添加一到两个集合产品。
为什么这只适用于alert()
函数,并且是否有一个修复方法可以通过一次单击将它们全部添加到购物车中,而不需要用户通过每个警报窗口单击?
发布于 2020-04-19 15:33:32
问题在于您发送的异步请求。
带有警报的循环可以工作,因为每次警报出现时脚本都会停止。同时,异步请求将被处理。
Shopify明确建议不要使用并行添加产品的模式,因为您可以阅读这里。
如果您想同时添加多个产品,可以使用一个请求添加它们,如shopify文档中所述:
jQuery.post('/cart/add.js', {
items: [
{
quantity: 1,
id: 794864229,
properties: {
'First name': 'Caroline'
}
},
{
quantity: 2,
id: 826203268,
properties: {
'First name': 'Mike'
}
}
]
});
发布于 2020-04-19 16:03:45
这是解决办法。正如弗里德所指出的,与其为集合中的每个产品创建一个请求,我还需要创建一个请求并循环遍历请求中的每个产品。下面是工作函数(减去数量检查,我需要添加它):
function addBundle2(){
jQuery.post('/cart/add.js', {
items: [
{% for kitproduct in collections['Pallets'].products %}
{
quantity: 1,
id: {{ kitproduct.variants[0].id }},
properties: {
}
},
{% endfor %}
]
});
window.location.reload(false);
}
https://stackoverflow.com/questions/61312960
复制相似问题