【发布时间】:2021-12-11 10:32:16
【问题描述】:
美好的一天,我正在尝试手动 ajax 这个
<a href="/cbg-gummies?add-to-cart=55337&convert_to_sub_55337=0" class="testing"> Add to cart </a>
这样做的目的是,它将 woocommerce 订阅中的一次性购买选项添加到购物车中。我正在尝试对其进行 ajax 处理,这样当您单击它时它不会刷新页面。
我发现了如何通过使用这些代码行手动对其进行 ajax 处理。 Reference here
(function($) {
$(document).on('click', '.testing', function(e) {
var $thisbutton = $(this);
try {
var href = $thisbutton.prop('href').split('?')[1];
if (href.indexOf('add-to-cart') === -1) return;
} catch (err) {
return;
}
e.preventDefault();
var product_id = href.split('=')[1];
var data = {
product_id: product_id
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.replace(
'%%endpoint%%',
'add_to_cart'
),
data: data,
beforeSend: function(response) {
$thisbutton.removeClass('added').addClass('loading');
},
complete: function(response) {
$thisbutton.addClass('added').removeClass('loading');
},
success: function(response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash
]);
$('a[data-notification-link="cart-overview"]').click();
}
}
});
return false;
});
})(jQuery);
上面的代码可以工作,但它会显示 ajax,但它显示的是每月订阅,而不是一次性购买。它应该显示一次性购买,因为&convert_to_sub_55337=0 这意味着选择了一次性订阅选项。
另外,单击控制台日志上的按钮后出现错误
Uncaught TypeError: $button is undefined
我是处理 ajax 的新手,所以我不确定这个问题
提前谢谢你!!
【问题讨论】:
-
使用 jquery(this) insted assiging button 希望它能起作用。
-
嗨@ArmanH,感谢您的评论。我试过了,但错误仍然存在,控制台日志错误不是优先级,直到 ajax 被整理出来,我可以找到修复它的方法。希望:D
-
你确定 convert_to_sub_55337 是正确的变量吗?如果您在浏览器中手动输入此网址,它是否正常工作?我认为不会将其传递给购物车。
-
嗨@MartinMirchev 感谢您的评论,我刚刚通过手动输入 URL 对其进行了测试,它通过一次性购买订阅选项将商品传递到购物车。所以'确定 convert_to_sub_55337' 正在工作
标签: ajax wordpress woocommerce woocommerce-subscriptions