使用cookie值设置基本cookie和警报

时间:2014-03-12 16:12:48

标签: javascript cookies

我试图设置一个基本的cookie。我已经离开警报了,所以我可以看看我是否成功了。我想存储当前网址的结尾。例如,我想存储MWFhUDfYpc9JYWmyapBDZvVYEz9rkMK6wSGZX4s。来自http://www.example.com/index.php?cid=MWFhUDfYpc9JYWmyapBDZvVYEz9rkMK6wSGZX4s

我已成功将Cookie设置为加载的网址,但无法进一步提升。

<script type="text/javascript">

function WriteCookie()
{
   cookievalue= window.location + ";";
   document.cookie="name=" + cookievalue;
   alert( cookievalue );
}

</script>

1 个答案:

答案 0 :(得分:2)

您尝试激活window.location,它返回当前页面的整个路径。这很好,但它会加载整个字符串http://www.example.com/index.php?cid=MWFhUDfYpc9JYWmyapBDZvVYEz9rkMK6wSGZX4s,而不仅仅是MWFhUDfYpc9JYWmyapBDZvVYEz9rkMK6wSGZX4s。最后,如果您只在cookie中存储1个密钥,则不需要在document.cookie字符串末尾添加分号。

示例jsfiddle: FIDDLE

这是修改后的代码,有一些错误处理。

<script type="text/javascript">
WriteCookie();
function WriteCookie() {
    try {
        var splt = window.location.split("=");
        document.cookie="name=" + splt[1];
        alert(splt[1]);
    } catch (err) {
        txt = "Error Found\n\n";
        txt += "Description: " + err.message + "\n\n";
        txt += "Click OK to continue.\n\n";
        alert(txt);
    }
}
</script>