簡體   English   中英

將變量設置為cookie值並重定向

[英]set variable to cookie value and redirect

我正在嘗試創建一個輸入,將您導航到以輸入值命名的目錄。 這部分有效,但是我需要將其存儲在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”。 重定向不起作用。

有沒有辦法解決這個問題? 謝謝。

首先,我將建議您像W3c-School中一樣創建一個函數來創建Cookie:

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

還有一個讀取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 "";
}

其次,您的文檔流程應為:首先保存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");  
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM