通过搜索值从一个html页面文本框到另一个html页面文本框点击使用cookie

Pass Search value from one html page text box to another html page text box on click using cookies?

本文关键字:文本 html 另一个 cookie 搜索 一个      更新时间:2023-09-26

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

我已经尝试了以下脚本,但它不像预期的那样工作:

Page 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>