前端cookie自动登录代码
时间: 2023-08-25 08:04:31 浏览: 40
以下是一个使用cookie实现自动登录的示例代码:
```javascript
// 登录成功后将登录状态存储到cookie中
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
setCookie("loggedIn", "true", 30);
// 读取登录状态的函数
function getCookie(name) {
var nameEQ = name + "=";
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, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
// 判断用户是否已经登录
if (getCookie("loggedIn")) {
// 自动填充账号密码并提交表单
document.getElementById("username").value = getCookie("username");
document.getElementById("password").value = getCookie("password");
document.getElementById("loginForm").submit();
}
```
在这个示例代码中,我们使用了`setCookie`函数将登录状态存储到cookie中,并设置了30天的过期时间。在读取登录状态的函数`getCookie`中,我们使用了JavaScript内置的`document.cookie`属性来读取cookie中的值。最后,在判断用户是否已经登录的代码中,我们调用了`getCookie`函数来读取cookie中的登录状态,如果用户已经登录,则自动填充账号密码并提交表单。在实际使用中,需要根据实际情况来修改代码。