使用cookie将值从一个html传递到另一个html不起作用?

时间:2017-11-01 13:43:13

标签: javascript jquery html cookies

我想在一个html中的搜索字段中获取用户输入,并在另一个html文件中显示输入。所以我发现最好的方法是将输入的输入保存为html file1中的cookie,并在html file2中检索cookie。

所以我使用了这些步骤

  1. 创建了一个cookie.js文件(添加了getcookie和setcookie函数)

  2. 在html1中设置Cookie

  3. 在html2中获取Cookie

  4. 这是我的cookie.js文件

    console.log("Cookie file activated");
    function getCookie(c_name)
    {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
    x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
    y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
    x=x.replace(/^\s+|\s+$/g,"");
    if (x==c_name)
     {
      return unescape(y);
     }
     }
    }
    
    function setCookie(c_name,value,exdays)
    {
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; 
    expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
    
    }
    

    在html1文件中

       <form action='Display.html' method='GET' class="search-container" name="site-search" role="search">
        <input type="text" name="sch" id="search-bar" placeholder="Search Name?">
        <button class="search-icon" id="searchbtn" 
        </button>
    </form>
    
     window.onload = function() {
        document.getElementById("search-bar").onkeyup = function() {
            setCookie("shared", this.value, 1);
             console.log(this.value)
        };
    };
    

    在html2文件中

    <h1 id="here">Display cookie value here</h1>
    
    
    var checkandupdate = function() {
           var shared = getCookie("shared");
           if(shared) {
            console.log(shared);
    
              document.getElementById("here").value = shared;
           }
    };
    
    window.onload = function() {
        int = setInterval(checkandupdate(),1000);
        checkandupdate();
    };
    

    它表明cookie文件在html1和2控制台日志中都被激活。但我无法在html2中显示搜索值。我做错了什么,如何解决?

0 个答案:

没有答案