javascript 如果 cookie 不存在警报和重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9145187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:43:38  来源:igfitidea点击:

If cookie does not exist alert and redirect

javascriptjquery

提问by Satch3000

I need to check if a cookie exists when the user lands on a page and if the cookie does not exist I need to popup an alert and then redirect to another page.

当用户登陆页面时,我需要检查 cookie 是否存在,如果 cookie 不存在,我需要弹出警报,然后重定向到另一个页面。

回答by Mala

if( $.cookie('cookiename') == null ) { 
    alert("OH NOES U NO HAS COOKIE");
    window.location.replace('http://url');
}

回答by Niet the Dark Absol

if( document.cookie.indexOf("cookiename=") < 0) {
    alert("Cookie not found, redirecting you.");
    location.href = "newpage.html";
}

Be careful not to use a cookie name that may be the end of another cookie name. If this is likely, you'll need to do a full cookie read, or use PHP instead.

注意不要使用可能是另一个 cookie 名称结尾的 cookie 名称。如果这是可能的,您将需要执行完整的 cookie 读取,或者改用 PHP。

回答by Satch3000

Using JavascriptReadCookie()Function

使用JavascriptReadCookie()功能

ReadCookie(), you realize immediately, is used to read a cookie.

ReadCookie(),你马上意识到,是用来读取cookie的。

You can read any cookies, provided they are being read on the same domain they were set at.

您可以读取任何 cookie,只要它们是在它们设置的同一个域上读取的。

<script type="text/javascript" language="JavaScript">
var acookie = ReadCookie("cookiename");
if(acookie.length == 0)
 { 
  //redirect somewhere 
 }
</script>