我正在学习 JavaScript 中的 session 和 cookie。我有一个表单,它接受一些数据并将其存储在 session 和 cookies 变量中,以显示在另一个页面(第二页)中,如下所示:
<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>
这是第二个.html 页面:
<html>
<body>
<script>
alert(sessionStorage["myKey"] + document.cookie);
</script>
</body>
</html>
但是,当我在警报函数中显示 session 和 cookie 变量时,它显示空变量。为什么我的 session 和 cookies 变量不起作用?
最佳答案
嗨,如果您想检查 session 存储的工作原理,您可以看到下面的代码... 它适用于单个页面。
如果有 2 个页面如果您只是从 file://协议(protocol)运行它,它将不起作用
<!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>
关于javascript - Javascript 中的 session 和 Cookie 未存储(不起作用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40012094/