gpt4 book ai didi

javascript - 如何在 javascript 中只显示一次警报?

转载 作者:行者123 更新时间:2023-12-01 03:06:02 25 4
gpt4 key购买 nike

我的情况是这样的:

if(window.location.pathname == '/shop/payment/checkout' || window.location.pathname == '/shop/detail' || window.location.pathname == '/shop') {
alert('Your data has been removed')
localStorage.removeItem("cartCache")
var _token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: baseUrl+'/shop/delete-cache',
data: {_token: _token},
success: function(response){
if(response.success==1)
window.location = "/shop";
},
error: function(request, status, error) {
console.log('error')
}
});
}

如果访问的url满足if条件则通过ajax删除session并重定向到url/shop

我的问题是,如果重定向到 url /shop,它会再次检查并再次显示警报消息。如此等等

我希望如果出现警报消息并重新加载到网址 /shop,它不再检查并显示警报消息

我该怎么做?

编辑:

给出答案后,我将代码包装如下:

if (localStorage.getItem("cartCache") !== null) {
...
}
else {
alert('Your data has been removed')
localStorage.removeItem("cartCache")
var _token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: baseUrl+'/shop/delete-cache',
data: {_token: _token},
success: function(response){
if(response.success==1)
window.location = "/shop";
},
error: function(request, status, error) {
console.log('error')
}
});
}
}

它没有按预期工作。

最佳答案

删除前,您可以先检查本地存储数据是否还在。将其放在警报之前:

if (localStorage.getItem("cartCache") === null) return;

...假设此代码位于函数内。但你明白了。或者您可以将其与已有的 if 结合起来(稍有改进):

if(['/shop/payment/checkout', '/shop/detail', '/shop'].includes(window.location.pathname) 
&& localStorage.getItem("cartCache") !== null) {
// ...etc.

关于javascript - 如何在 javascript 中只显示一次警报?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46181159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com