需要考虑的问题:
1 自动登录如何实现
2 点击登录如何实现
3 用户名写进cookie
4 自动获取用户名
具体解决方案:
1 是否在自动登录有效期内
首先进页面先发送请求,后台获取cookie的值进行判断,如果存在则自动登录;
如果不存在(说明是新用户),注册->登录;
如果存在但已过期,获取cookie,自动写入用户名,仅让客户重新输入密码。
2 是否勾选自动登录
2-1用户名、密码已填写完毕(填写正确),如果用户勾选自动登录(假设有效期10天)->点击登录按钮->验证成功->写入cookie(10天)->跳转页面->后台记录10天->10天之内会自动登录(不需要手动输密码);
用户名、密码已填写完毕(填写正确),如果用户不勾选自动登录->点击登录按钮->验证成功->写入cookie(临时cookie,即关闭当前浏览器全部页面后,cookie即自动删除)->跳转页面->下次需手动重新登陆
源代码(仅适用于我自己):
//cookie已存在(进入页面先判断)
if($.cookie('userName')) {
$('#userName').val($.cookie('userName'));
$('#password').focus();
}else {
$('#userName').focus();
}
//login
var loginLock = [false, false];
$('.loginBtn').on('click', function() {
var userName = $('#userName').val(),
password = $('#password').val(),
autoLogin = $('#autoLogin').prop('checked');
if(userName) {
loginLock[0] = true;
}else {
loginLock[0] = false;
}
if(password) {
loginLock[1] = true;
}else {
loginLock[1] = false;
}
//前台验证
if(!loginLock[0]) {
popTip({
text: '请输入用户名',
type: 'error'
});
}
if(!loginLock[1]) {
popTip({
text: '请输入密码',
type: 'error'
});
}
//后台验证
if(loginLock[0] && loginLock[1]) {
request({
type: 'post',
url: 'login/login',//发送请求
params: $('.submit').serialize(),
success: function(data) {//请求成功
if(autoLogin) {//√勾选自动登录
$.cookie('userName', userName, {path: '/', expires: 10});
}else {//×不勾选自动登录
$.cookie('userName', '');
}
if(data.user.SkinId) {//复杂版
window.location.href = "../../index.html";
}else {//简洁版
window.location.href = "../../web_mini/index.html";
}
},
error: function(data) {//请求成功,但用户名或密码有误
if(data['showCode']) {
$('.vcodeCtn').show();
}
popTip({
text: data.message,
type: 'error'
});
}
});
}
$('.vcodeImg').trigger('click');//刷新验证码
});
//vcode
$('.vcodeImg').on('click', function() {
$(this).attr({'src': '../../../ImageCode?'+Math.random()});
});
autoLogin();//是否在自动登录有效期内
function autoLogin() {
request({
type: 'get',
url: 'user/isLogin',
success: function(data) {
if(data.user.SkinId) {//复杂版
window.location.href = "../../index.html";
}else {//简洁版
window.location.href = "../../web_mini/index.html";
}
},
error: function(data) {
/*popTip({
text: data['message'],
type: 'error'
});*/
}
});
}
//请求统一的方法
function request(options) {
var _default = {
type: 'get',
preUrl: '../../',
url: '',
params: {},
dataType: 'json',
success: function() {},
error: function() {}
},
_options = $.extend({}, _default, options);
var type = _options.type,
url = _options.preUrl + _options.url,
params = options.params,
dataType = _options.dataType,
success = _options.success,
error = _options.error;
$.ajax({
type: type,
url: encodeURI(url),
data: params,
dataType: dataType,
cache : false,
success: function(data) {
if(!data.status) {
success(data);
}else {
error(data);
}
}
});
}
//弹窗提示
function popTip(options) {
var _default = {
text: '成功',
type: 'success',
$obj: $('.noty')
},
_options = $.extend({}, _default, options);
_options.$obj.noty({
text: _options.text,
type: _options.type
});
}