javascript - 使用 cookie 将搜索值从一个 html 页面文本框传递到另一个 html 页面文本框?

标签 javascript html cookies

我想使用 cookie 将搜索查询从一个 html 页面文本框传递到另一个 html 页面文本框。

我尝试了以下脚本,但它没有按预期工作:

第1页

<input type="text" value="" name="s" id="s1" />
<input id="btnSave" type="button" value="Search" onclick="Redirect();"/>

<script type="text/javascript">
    function Redirect() {
        var x = document.getElementById("s1").value;
        document.cookie = x;
        window.location.href = 'Result.html';
    }
</script>

第 2 页

<script>
    function getcookie() {
        document.getElementById("#s").value = document.cookie;
    }
</script>


<body onload="getcookie();">
<input id="s" type="text" />
</body>

最佳答案

您应该设置 cookie 及其过期时间(这并不重要,但当您想要检索甚至关闭浏览器并且在浏览器打开时再次需要它时很有用)。 还有一件事,当您获取 cookie 值时,它会给出包含所有 cookie 值的字符串,因此请自定义它以获得所需的值。

设置 Cookie

function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    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 "";
}

一起,在您现有的解决方案中工作

第 1 页

<script type="text/javascript">
    function Redirect() {
        var x = document.getElementById("s1").value;
        setCookie("s",x,2);
        window.location.href = 'Result.html';
    }
</script>

第 2 页

<body onload="document.getElementById('s').value =getCookie('s')">
<input id="s" type="text" />
</body>

关于javascript - 使用 cookie 将搜索值从一个 html 页面文本框传递到另一个 html 页面文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32667231/

相关文章:

javascript - D3 定位在 div 内

javascript - AngularJS XSRF 策略不支持 cookie 路径

Javascript - 检查 cookie 是否已设置

javascript - 如何请求 node.js 中的垃圾收集器运行?

java - 将 &lt;script&gt; 添加到 <head> from Play Framework 2 中的 scala 模板标签

asp.net - WebForms 在自动回发期间不包括表单中的电子邮件输入类型

html - 旋转具有透视错误的 3d 立方体?

html - 如何在固定宽度的 div 中居中动态宽度按钮?

php - Curl - 获取 JSESSIONID

javascript - jQuery的scrollTop不触发