Javascript-检查是否设置了cookie
Javascript - Check if cookie is set
大家好,如果点击按钮设置了cookie,我想将用户重定向到另一个页面。
<a href="" onClick="SetCookie('pecCookie','dit is een cookie','-1')"><button type="button" name="accept" class="btn btn-success">Button Text</button>
<script>
function SetCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+365)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) +
("; path=/")
location.reload()
}
if
</script>
Works,我也在php中得到了if语句,但由于wordpress问题,我希望它在javascript中。在php中,它看起来是这样的。
<?php
$cookie_name = "anyname";
$cookie_value = "anycontent";
If (isset($_COOKIE[$cookie_name])) {
// action if cookie is set
}
?>
我似乎无法用javascript来理解它,我还四处查看了网络
完成此操作后:
<a href="" onClick="SetCookie('pecCookie','dit is een cookie','-1')"><button type="button" name="accept" class="btn btn-success">Button Text</button>
<script>
function SetCookie(c_name,value,expiredays) {
var exdate=new Date()
exdate.setDate(exdate.getDate()+365)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) +
("; path=/")
location.reload()
}
mycookieValue = getCookie("pecCookie")
if(mycookieValue) {
window.location = "193.91.113.21/downloads/";
}
function getCookie(c_name) {
var re = new RegExp(c_name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
</script>
即使没有cookie ,它也会继续重定向
这里有一个函数,用于获取javascript中的cookie值。
mycookieValue = getCookie("mycookieName")
if(mycookieValue)
{
//Your code here
}
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
我建议您使用jQuery cookie.js库。你可以从这里下载。。https://github.com/carhartl/jquery-cookie
示例:
//Set Cookie
$.cookie('userName', 'John');
//Read Cookie Value
var username= $.cookie('userName');
console.log(username);
//Remove a cookie
$.removeCookie('username');
//Cookie is removed then above line will return true
//Check cookie in if else
if(username){
console.log(username);
}
// or you can do this also
if(username=='John'){
console.log('User Name is '+username);
}
希望这对你有帮助。
相关文章:
- 在jquery中为显示/隐藏设置cookie
- 如何为后台更改程序代码设置cookie
- Cookie 设置为 iframe javascript 中的父窗口
- 无法使用 jQuery Cookie 设置 Cookie
- Javascript 将 Cookie 设置为在下拉列表中获取值
- jquery css样式切换器将cookie设置为css
- 将cookie设置为与弹出窗口集成
- 如果浏览器关闭,如何将FireFox cookie设置为持久
- 将 Cookie 设置为复选框状态
- 使用cookie设置/获取输入值
- 检查是否有cookie设置,如果没有输出脚本
- PHP cookie设置为重定向,googlebot也重定向-如何阻止这种情况
- jquery中基于输入框的cookie设置
- JS Cookie设置在2个地方,不覆盖第一个设置
- 如何将cookie设置为WebBrowser控件
- 我如何使用我的代码将cookie设置为在x天后过期
- Javascript cookie设置不工作
- 将cookie设置为表单条目的值
- 在页面加载时立即停止cookie设置
- Cookie设置不正确