我的情况是这样的:
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')
}
});
}
如果访问的网址符合if
的条件,那么它将通过ajax删除会话并重定向到网址/shop
我的问题是如果重定向到网址/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')
}
});
}
}
它没有按预期工作。
答案 0 :(得分:2)
在删除之前,您可以先检查本地存储数据是否仍然存在。把它放在alert
:
if (localStorage.getItem("cartCache") === null) return;
...假设此代码在函数内。但是你明白了。或者您可以将它与您已经拥有的if
(稍微改进)结合起来:
if(['/shop/payment/checkout', '/shop/detail', '/shop'].includes(window.location.pathname)
&& localStorage.getItem("cartCache") !== null) {
// ...etc.