我正在学习JavaScript中的会话和cookie。我有一个需要一些数据并将其存储在会话和cookie变量中的表单,该变量将在另一页(第二页)中显示,如下所示:
<html>
<body>
<form action="second.html" onsubmit="return myFunction();">
Enter a session variable: <input id="sess" type="text" />
</br>
Enter a coockie variable: <input id="cookiess" type="text" />
</br>
<input type="submit" />
</form>
<script>
function myFunction() {
document.cookie = "username="+document.getElementById("cookiess").value + "; expires=Fri, 14 Oct 2016 12:00:00 UTC";
sessionStorage["myKey"] = document.getElementById("sess").value;
return true;
}
</script>
</body>
</html>
这是second.html页面:
<html>
<body>
<script>
alert(sessionStorage["myKey"] + document.cookie);
</script>
</body>
</html>
但是,当我在警报功能中显示会话和cookie变量时,它将显示空变量。为什么我的会话和Cookie变量不起作用?
最佳答案
您好,如果您想查看会话存储的工作方式,可以看到以下代码...
其用于单个页面。
如果有2个页面如果仅从file://协议运行此页面,它将无法正常工作
<!DOCTYPE html>
<html>
<head>
<script>
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount)+1;
sessionStorage["myKey"] = sessionStorage.clickcount;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " + sessionStorage.clickcount + " time(s) in this session."+sessionStorage["myKey"];
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter is reset.</p>
</body>
</html>