简体   繁体   English

用户关闭弹窗后如何申请优惠券代码?

[英]How to apply coupon code after users close popup?

Background:背景:

I have a popup that request emails from users.我有一个要求用户发送电子邮件的弹出窗口。 Should they complete the email submit, I would like to apply a coupon code automatically should they subsequently make a purchase at checkout.如果他们完成电子邮件提交,如果他们随后在结账时购买,我想自动应用优惠券代码。

For coupon codes to be applied, all users have to do is access a link with /?coupon_code=xxxx at the end of the url.对于要应用的优惠券代码,所有用户所要做的就是访问 URL 末尾带有/?coupon_code=xxxx的链接。

This code was obtained here: GET a coupon code via URL and apply it in WooCommerce Checkout page此代码是在此处获得的: 通过 URL 获取优惠券代码并将其应用于 WooCommerce Checkout 页面

Problem:问题:

How do I add the /?coupon_code=xxxx when a user closes the popup?当用户关闭弹出窗口时,如何添加/?coupon_code=xxxx

What I have tried:我尝试过的:

I have tried to use the solution offered here ( Change URL without refresh the page ).我尝试使用此处提供的解决方案( 更改 URL 而不刷新页面)。 This is what I inserted.这是我插入的。

history.pushState(null, '', '/?coupon_code=xxxx');

While this works in changing the url, I find that the coupon code is not applied at checkout.虽然这适用于更改 url,但我发现在结帐时未应用优惠券代码。 However, if I manually entered the full url and refreshed the page eg.但是,如果我手动输入完整的 url 并刷新页面,例如。 www.test.com/?coupon_code=xxxx , the coupon code will be applied at checkout. www.test.com/?coupon_code=xxxx ,优惠券代码将在结账时使用。

Thank you.谢谢你。

Would making an AJAX/fetch request work in this scenario?在这种情况下,AJAX/fetch 请求会起作用吗? I'm not entirely sure I understand the question, but perhaps you could try:我不完全确定我理解这个问题,但也许你可以尝试:


let onClose = async () => {
    let response = await fetch(‘/?coupon_code=xxxx’);
    let data = await response.json();
    return data; //returns the result of your request to the coupon code URL
}

hope this helps!希望这可以帮助!

Edit: to explain why this works编辑:解释为什么这有效

When you change the history state, all that is being affected is the browsers local state.当您更改历史状态时,受影响的只是浏览器的本地状态。 To apply the coupon code, you actually need to make an http request to the URL you've provided, which is what the fetch API does.要应用优惠券代码,您实际上需要向您提供的 URL 发出 http 请求,这正是 fetch API 所做的。 It's asynchronous, which is why we're using async/await.它是异步的,这就是我们使用 async/await 的原因。 It could also be done by chaining .then(), if you preferred.如果您愿意,也可以通过链接 .then() 来完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM