开发者

Setting cookie leads to an unexpected behaviour

I have a multilingual website with the possibility to switch between German and English. I want to store the chosen language in a cookie so that the visitor don't have to switch it over and over again to his prefered language when he visits the website next time. Unfortunately I have a strange behaviour with that. It looks like this:

I have a link for switching the language (onclick). This function looks like this:

function storeLanguage(lang)  {
    /*deletes the cookie? */
    document.cookie = "MYCOOKIE=; expires=Thu, 01-Jan-70 00:00:01 GMT;";
    var ablauf = new Date();
    var expTime = ablauf.getTime() + (60 * 24 * 60 * 60 * 1000); //Cookie for 60 days
   ablauf.setTime(expTime);

   if (lang == 'en')  {
            document.cookie = "MYCOOKIE=EN; expires=" + ablauf.toGMTString() + ";";
   }
   else  {
       document.cookie = "MYCOOKIE=DE; expires=" + abla开发者_如何学Gouf.toGMTString() + ";";
   }
}

Firebug says that it jumps into the right IF-branch, so when I click "German", this part will be executed "MYCOOKIE=DE", otherwise the english branch. This looks right. But when I get to any web page of my website (for test I chose the index site) and execute an

alert(document.cookie);

I suddendly get as result at the German web page "MYCOOKIE=EN", although it should be "MYCOOKIE=DE" because the function jumped into the right IF-branch (else branch). When I switch to English language, I get as result on the english web page "MYCOOKIE=DE; MYCOOKIE=EN". So suddendly there are two cookies with the same name. So the values of the cookies are not just inverted, and not deleted right, but totally crap. Can anybody explain what's wrong in my code which leads to this behaviour?


Make sure that you are properly setting the path of the cookie as well. For example if the language of your site is embedded in the URL (IE: http://yoursite.com/en/index.html), you may be setting a cookie to only be valid if the path contains "/en". Full cookie setting syntax looks like this:

document.cookie = 'mycookie=somevalue; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜