前提
1、jquery-3.4.1.js
2、query.base64.js
3、query.cookie.js
引用
<script src="js/jquery-3.4.1.js" type="text/javascript"></script> <script src="js/jquery.base64.js" type="text/javascript"></script> <script src="js/jquery.cookie.js" type="text/javascript"></script>
代码
//if exists that show User Account By Cookie showUserAccountByCookie(); $(".form-signin").submit(function(){ var userName=$("#userName").val(); var passWord=$("#passWord").val(); var str_data={"UserName":userName,"Password":passWord}; $.ajax({ type: 'get', async : false, dataType: 'jsonp', url: "http://localhost:8078/springBoot/User", jsonpCallback: "handleCallback", data:str_data, success: function(result){ //console.log(result.code); if(result.status){ $("#error_msg").css("display","none"); saveAccountByCookie(userName,passWord) //removeAccountByCookie(); // location.href="index.html"; }else{ $("#error_msg").text("账号/密码错误,请重新输入"); $("#error_msg").css("display","block"); } }, error:function(result){ //console.log("error"); } }); return false; }); function saveAccountByCookie(UserName,Password){ if($("#chk_remeber").prop("checked")){ console.log("saveAccountByCookie-->checked"); $.cookie('sysUser', 'true',{ expires: 7 }); $.cookie("sysUserName", UserName, { expires: 7 }); $.cookie("sysPassword", $.base64.encode(Password), { expires: 7 }); }else{ removeAccountByCookie(); } } function removeAccountByCookie(){ $.cookie('sysUser', 'false',{ expires: -1 }); $.cookie("sysUserName", null, { expires: -1 }); $.cookie("sysPassword", null, { expires: -1 }); } function showUserAccountByCookie(){ console.log($.cookie('sysUser')); console.log("加密后:"+$.cookie("sysPassword")); console.log("解密后:"+$.base64.decode($.cookie("sysPassword"))); if($.cookie('sysUser')=="true"){ $("#userName").val($.cookie("sysUserName")); $("#passWord").val($.base64.decode($.cookie("sysPassword"))); $("#chk_remeber").prop("checked",true); } }
总结:
1、设置cookie并设置过期时间(expires单位:天): $.cookie([key], [value], { expires: [num] });
2、清空cookie
$.cookie([key], [value], { expires: -1 }); 或者 $.cookie([key], null);
3、base64加密、解密
$.base64.encode()/ $.base64.decode()