我正在尝试在document.cookie中设置多个cookie,但是不幸的是,我的代码将cookie值显示为null和undefined。我的代码如下:
<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>
从技术上讲,我认为代码没有错误。请告诉我我哪里出了问题
最佳答案
尝试将字符串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>