Setting a testing a cookie with Javascript issues
So at the moment I am working on setting a cookie in the user's browser... this is how I have done so:
var cookiename = "benjaminpotter_welcome";
var cookievalue = "visited";
var date = new Date();
date.setTime(date.getTime()+604800000)
var cookieExpiration = date.toGMTString();
var cookiepath = "; path=/";
var myCookie = cookiename + "=" + cookievalue + ";expires=" + cookieExpiration + path;
document.cookie = myCookie;
And this is how I have attempted to receive it:
function readCookie(benjaminpotter_welcome) {
cookieName = cookieName.replace(/([.\\+\-*:\/?!|^${}()\[\]])/g, '\\$1');
var re = new RegExp('[; ]'+cookieName+'=([^\\s;]*)');
var sMatch = (' '+document.cookie).match(re);
if (cookieName && sMatch){
var cookieval = unescape(sMatch[1]);
}else{
var cookieval = '';
};
};
The thing is that it isn't working at all...
Here is what I want to happen... I want to set a cookie in the user's browser called 'benjaminpotter_welcome' having the value 'visited'.
Then I need to request that cookie (on the next page load of course) and test to see whether it = 'visited', upon which code will be executed (or in my case not executed.
Here is the part of my website that is not working currently when attempting to use this code:
<script type="text/javascript">
function readCookie(benjaminpotter_welcome) {
cookieName = cookieName.replace(/([.\\+\-*:\/?!|^${}()\[\]])/g, '\\$1');
var re = new RegExp('[; ]'+cookieName+'=([^\\s;]*)');
开发者_运维知识库 var sMatch = (' '+document.cookie).match(re);
if (cookieName && sMatch){
var cookieval = unescape(sMatch[1]);
}else{
var cookieval = '';
};
};
$(document).ready(function(){
$("#thanks").fadeOut(0);
$("#overlay_big").fadeOut(0);
readCookie();
if(cookieval == 'visited'){
}else{
$("#overlay_big").delay(2000).fadeIn(1000);
};
});
</script>
You are setting cookieval
inside the method, which makes it a private variable. Try:
function readCookie(cookieName) {
cookieName = cookieName.replace(/([.\\+\-*:\/?!|^${}()\[\]])/g, '\\$1');
var re = new RegExp('[; ]'+cookieName+'=([^\\s;]*)');
var sMatch = (' '+document.cookie).match(re);
return cookieName && sMatch ? unescape(sMatch[1]) : '';
};
and your DOM-ready:
$(document).ready(function(){
$("#thanks").fadeOut(0);
$("#overlay_big").fadeOut(0);
var cookieval = readCookie("benjaminpotter_welcome");
if(!cookieval == 'visited'){
$("#overlay_big").delay(2000).fadeIn(1000);
};
});
should do it.
If you understood your code, I can recommend the jquery.cookie plugin to work with cookies with javascript.
精彩评论