模板及PHP代码都有,主要使用ajax异步请求提交表单,再用$_COOKIE实现记住密码的功能,js这边使用的是vue,整体上比较简单,代码也比较少。
**login.html**
![](https://box.kancloud.cn/248eb7699c830d13e974907aa6d523a1_509x59.jpg)
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
<script src="js/vue.js"></script>
</head>
<body>
<form id="form" action="login.php" method="post">
<div v-if="isremember === 'yes'">
<button type="button" @click="login">登录</button>
</div>
<div v-else>
<input name="username" type="text" v-model="username" :placeholder="usernameTip">
<input name="password" type="password" v-model="password" :placeholder="passwordTip">
<label><input name="remember" type="checkbox" v-model="remember">记住密码</label>
<button type="button" @click="login">登录</button>
</div>
</form>
<script>
var form = new Vue({
el: '#form',
data: {
username: '',
password: '',
remember: false,
isremember: 'no',
usernameTip: '请输入用户名',
passwordTip: '请输入密吗'
},
methods: {
login: function() {
if(/(password.*username)/.test(document.cookie)) { // 记住密码
window.location.href = 'index.php';
} else {
var errorTip = '';
if(this.username=='') {
errorTip += '用户名没填;';
}
if(this.password=='') {
errorTip += '密码没填;';
}
if(errorTip) {
alert(errorTip);
} else {
this.$el.submit();
}
}
}
}
});
if(/(password.*username)/.test(document.cookie)) {
form.$data.isremember = 'yes';
form.$data.username = 'tom';
form.$data.password = '123456';
}
</script>
</body>
</html>
~~~
**login.php**
~~~
<?php
header('Content-type: text/html;charset=utf-8');
$username = $_POST['username'];
$password = md5($_POST['password']);
if(isset($_POST['remember'])) { // 判断是否设置了remember
$remember = $_POST['remember'];
}
// 判读用户名、密码
if($username=='tom' && $password=='e10adc3949ba59abbe56e057f20f883e') {
// 判断是否记住密码,使用的是cookie保存,会暴露给用户
if(isset($remember)) {
setcookie('password', $password, time()+3600);
}
setcookie('username', $username, time()+3600); // 保存1小时
echo '<script>alert("登录成功!");window.location.href="index.php";</script>';
// 也可以使用header方式跳转 header('Location: index.php');
} else {
echo '<script>alert("登录失败!");window.history.back();</script>';
}
?>
~~~
**index.php**
![](https://box.kancloud.cn/a0c1fb49a92495952f01a1d3be23dc74_278x59.jpg)
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
welcome <strong><?php echo $_COOKIE['username']; ?> </strong>
<button type="button" onclick="logout()">退出</button>
<button type="button" onclick="logoff()">注销</button>
<script>
function logout() {
window.location.href = 'login.html';
}
function logoff() {
if(/(password.*username)/.test(document.cookie)) {
document.cookie = 'username="";expires='+new Date((Date.parse(new Date())-1)).toGMTString();
document.cookie = 'password="";expires='+new Date((Date.parse(new Date())-1)).toGMTString();
}
window.location.href = 'login.html';
}
</script>
</body>
</html>
~~~