我想使用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>
答案 0 :(得分:1)
你应该设置一个cookie及其到期时间(当你想要关闭borwser并且在浏览器打开时再次需要它时,不重要但有用)。 还有一件事,当你获得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>
答案 1 :(得分:0)
交配,请使用以下代码:
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;}
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 "";}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}}