[英]How can I display alert only once in javascript?
我的情况是这样的:
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删除会话并重定向到url /shop
我的问题是,如果重定向到url /shop
,它将再次检查并再次显示警报消息。 等等
我想要警报消息出现并重新加载到url /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')
}
});
}
}
它不能按预期工作。
删除之前,您可以先检查本地存储数据是否仍然存在。 将此放在alert
之前:
if (localStorage.getItem("cartCache") === null) return;
...假设此代码在函数内。 但是你明白了。 或者,您也可以将其与( if
有所改善)结合使用:
if(['/shop/payment/checkout', '/shop/detail', '/shop'].includes(window.location.pathname)
&& localStorage.getItem("cartCache") !== null) {
// ...etc.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.