我正在尝试在document.cookie中设置多个cookie,但遗憾的是我的代码将cookie值显示为null且未定义。我的代码如下:
<script>
function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
var cookie_string = name + "=" + escape ( value );
if ( exp_y )
{
var expires = new Date ( exp_y, exp_m, exp_d );
cookie_string += "; expires=" + expires.toGMTString();
}
if ( path )
cookie_string += "; path=" + escape ( path );
if ( domain )
cookie_string += "; domain=" + escape ( domain );
if ( secure )
cookie_string += "; secure";
document.cookie = cookie_string;
}
</script>
<script>
alert(setCookie( "username", "Miron" ));
alert(setCookie( "username", "Mirion", 2003, 01, 15 ));
alert(setCookie("username", "John Smith", 2003, 01, 15, "","elated.com", "secure"))
</script>
我在技术上看不到代码中的错误。请告诉我哪里出错了
答案 0 :(得分:0)
您似乎试图调用setCookie
,但您定义的方法称为set_cookie
。如果在方法中添加dubugger
行并运行它 - 您是否正在调试调试语句?要更正,请将功能名称更改为setCookie
或将呼叫更改为set_cookie
。
此外,该功能似乎没有返回任何内容,因此您的警报将为undefined
(当它运行时)。在调用setCookie
方法后,只需在控制台中尝试使用document.cookie,您就会看到已设置了值。
答案 1 :(得分:0)
尝试return
将字符串display in alert
更改为set_cookie
,并将您的函数名称setCookie
更改为 <script>
function setCookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
var cookie_string = name + "=" + escape ( value );
if ( exp_y )
{
var expires = new Date ( exp_y, exp_m, exp_d );
cookie_string += "; expires=" + expires.toGMTString();
}
if ( path )
cookie_string += "; path=" + escape ( path );
if ( domain )
cookie_string += "; domain=" + escape ( domain );
if ( secure )
cookie_string += "; secure";
document.cookie = cookie_string;
return cookie_string;//or document.cookie
}
</script>
<script>
alert(setCookie( "username", "Miron" ));
alert(setCookie( "username", "Mirion", 2003, 01, 15 ));
alert(setCookie("username", "John Smith", 2003, 01, 15, "","elated.com", "secure"))
</script>
。
{{1}}