I am reading and setting a cookie using JavaScript in the BODY onload
and onunload events respectively. This works fine.
However when I use ASP to set the cookie under some condition where I
want to override the last value set in the onunload event, it has no
effect. The next onload still has the old value.
Any ideas? The following code simulates the problem I experience.
--------------------------------------------------
Filename = JSCookie.asp
--------------------------------------------------
<%@ Language=VBScript %>
<%
Option Explicit
%>
<script LANGUAGE="JavaScript">
var Value;
function setCookie(name, value, expire) {
document.cookie = name + "=" + escape(value)
+ ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))
}
function getCookie(Name) {
var search = Name + "="
if (document.cookie.length > 0) { // if there are any cookies
offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
end = document.cookie.indexOf(";", offset)
// set index of end of cookie value
if (end == -1)
end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
}
}
function Read()
{
Value = getCookie("Value");
// default to 1 if no cookie set yet (i.e. 1st time through)
if (!Value)
Value = 1;
alert("Read Value = " + Value);
}
function Change(NewValue)
{
Value = NewValue;
}
function Write()
{
setCookie("Value", Value, null);
alert("Wrote Value = " + Value);
}
</script>
<% Response.Cookies("Value") = 1 %>
<HTML>
<HEAD>
</HEAD>
<BODY onload="Read();" onunload="Write();">
<P><a href="javascript:Change(1);">Set Value to 1</a></P>
<P><a href="javascript:Change(2);">Set Value to 2</a></P>
<BR>
<P><a href="JSCookie.asp">Click Here to Reload Page</A>
</BODY>
</HTML>
--------------------------------------------------
Thanks,
Michael Levy