我是JavaScript新手。我已经创建了登录页面,我知道如何在cookie中保存数据现在我想知道当我点击登录按钮并在下一页显示时如何从cookie中检索数据。我试过但我无法得到解决方案。任何人都可以帮我解决这个问题。
我添加了以下代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login Page</title>
</head>
<body>
<script>
var myCookies = {};
function saveCookies()
{
myCookies["_mail"] = document.getElementById("mail").value;
document.cookie="";
var expiresAttrib = new Date(Date.now()+60*1000).toString();
var cookieString = "";
for(var key in myCookies)
{
cookieString = key+"="+myCookies[key]+";"+expiresAttrib+";";
document.cookie = cookieString;
}
document.getElementById("abc").innerHTML = document.cookie;
}
</script>
<div class="container">
<h1>LOGIN FORM<h1>
<p><input type="email" id="mail" placeholder="Enter Email" name="uname" required></p>
<p><input type="password" id="Pass" placeholder="Enter Password" name="psw" required></p>
<button id="btnLogin" class="login" onclick="saveCookies()" >Login</button>
<p id="abc">
</p>
</div>
</body>
</html>
答案 0 :(得分:0)
从cookie获取数据需要使用regex
来解析值并获得结果。例如
document.cookie = "test1=Hello";
document.cookie = "test2=World";
var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
console.log(cookieValue) // World
了解更多详情GoTo MDN Cookie