读取cookie数据并重定向

3

我需要一些关于读取cookie的帮助。我的网站是双语的,因为我不想基于IP更改语言,所以我需要能够设置一个名为“_lang”的cookie,并查看内容是否为“en”或“jp”。我可以设置cookie及其内容,没有问题,但我无法找出读取cookie内容的语法;这是我第一次尝试。

function createCookie(name,value,days) {
if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}


function GetCookie(name) {
  var arg=name+"=";
  var alen=arg.length;
  var clen=document.cookie.length;
  var i=0;
  while (i<clen) {
    var j=i+alen;
    if (document.cookie.substring(i,j)==arg)
      return "here";
    i=document.cookie.indexOf(" ",i)+1;
    if (i==0) break;
  }
  return null;
}

var visit=getCookie("_lang");
var rc=readCookie("_lang");
if (visit==true){
        if (rc == "jp"){
            window.location = "http://jp.mywebsite.com";
        }

        else if (rc == "en"){
            window.location = "http://www.mywebsite.com";
        }
}
else if (visit==null){
    document.title = "Welcome to MyWebsite!"
    document.getElementById('welcomeLB').style.display='block';
    document.getElementById('behindLightBox').style.display='block';
}
1个回答

0
我建议使用插件。https://github.com/pavelkukov/localdata
在您的情况下:
var lang_cookie = readCookie('user_lang') ;

if( lang_cookie && lang_cookie !== null && lang_cookie !== 'undefined')
{
     if(lang_cookie === 'en')
     {
          document.location = 'http://en.mysite.com';
     }
     document.location = 'http://jp.mysite.com';
}

document.location = 'http://en.mysite.com';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接