简体   繁体   中英

set variable to cookie value and redirect

I'm trying to create an input that navigates you to the directory named after the input value. This part works, but I need to store this in a cookie and redirect the user when they return to the page. So far I have this:

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;
    }
  }   
}

The cookie is created, but I get "Uncaught ReferenceError: nameEQ is not defined" in the console. The redirect does not work.

Is there a way to fix this? Thanks.

First I will Suggest you to create a function to create A cookie as you have in the W3c-School:

    function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

And also a function for reading the cookie :

    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 "";
}

Second the flow of your document should be that first you are saving the 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");  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM