将变量设置为cookie值并重定向

时间:2015-07-06 03:44:35

标签: javascript variables cookies

我正在尝试创建一个输入,将您导航到以输入值命名的目录。这部分有效,但我需要将其存储在cookie中,并在用户返回页面时重定向。到目前为止,我有这个:

function sendanswer(e) {
  if (e.keyCode === 13) {
    e.preventDefault();
    var answer = document.answerarea.input.value;

    if (answer) {
      window.location.href = answer;
      //SET COOKIE WITH NAME redirectPath
      document.cookie = "redirectPath=" + answer;
    }
  }
}
document.answerarea.input.onkeypress = sendanswer;

window.onload=function(){
  var kuki = "redirectPath="; //NAME OF COOKIE WE SET
  var cookies = document.cookie.split(';');

  for(var i = 0; i < cookies.length; i++) {
    var c = cookies[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);

    if (c.indexOf(kuki) == 0){
       var path = c.substring(nameEQ.length, c.length);
       //MOVE USER TO STORED PATH
       document.location.href = path;
    }
  }   
}

已创建cookie,但我在控制台中收到“Uncaught ReferenceError:nameEQ未定义”。重定向不起作用。

有没有办法解决这个问题?感谢。

1 个答案:

答案 0 :(得分:0)

首先我建议你创建一个函数来创建一个cookie,就像在W3c-School中一样:

    function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

还有一个阅读cookie的功能:

        function sendanswer(e) {
  if (e.keyCode === 13) {
    e.preventDefault();
    var answer = document.answerarea.input.value;

    if (answer) {
      //SET COOKIE WITH NAME redirectPath
      setCookie("redirectPath=" , answer);
      window.location.href = answer;
    }
  }
}

window.onload=function(){
  var kukiResult = getCookie("redirectPath");  
}

其次,文档的流程应该是首先保存cookie:

{{1}}