I am having trouble setting and deleting cookies in php Ive got no problem.. in javascript eh.. lots I know this question is everywhere but all the answers I come across seem to bring me the same fate so I have no idea whats going on.. this is what I have currently.
SetCookie("username",ztsUser,14,'/', '');
function SetCookie (name,value,expires,path,domain,secure) {
document.cookie = name + "=" + escape (value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
(开发者_运维技巧(path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
the error:
expires.toGMTString is not a function
The whole lot of cookie functions I have.. is:
var today = new Date();
var expiry = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000);
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) { endstr = document.cookie.length; }
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal (j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function DeleteCookie (name,path,domain) {
if (GetCookie(name)) {
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
function SetCookie (name,value,expires,path,domain,secure) {
document.cookie = name + "=" + escape (value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
if anyone knows a better method Im all ears.. but this is what I got at the moment, I need to set, update, delete, get the value of.. cookies
toGMTString
has been deprecated. Try toUTCString
instead:
function SetCookie (name,value,expires,path,domain,secure) {
document.cookie = name + "=" + escape (value) +
((expires) ? "; expires=" + expires.toUTCString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
You're also passing a number (14
) when the function expects a Date (expires.toUTCString
):
SetCookie("username", ztsUser, 14, '/', '');
What is 14 intended to be? 14 days? Assuming that, you can add this at the top of the function to support both numbers and dates:
if ('number' === typeof expires) {
expires = new Date(new Date().getTime() + expires * 86400000);
}
86400000
is the number of milliseconds in a day -- 24 * 60 * 60 * 1000
.
There are already a number of great libraries for handling cookies in JS. Why not use one of them? Just go to your favorite search engine and enter "javascript cookie library" to find one.
精彩评论