大家好,如果通过点击按钮设置了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>
工作,我也得到了PHP中的if语句,但我想在javascript中因为wordpress问题。在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
,它也会继续进行重定向答案 0 :(得分:1)
这是一个用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;
}
答案 1 :(得分:0)
我建议你使用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);
}
希望这会对你有所帮助。