最近做了记住密码功能,用localStorage跟cookie都尝试用了一下,感觉都挺好哈,很方便,特此记录
html代码:
<input type="text" id="userName" placeholder="账号"> <input type="password" id="password" placeholder="密码"/> <input class="remember" type="checkbox" style=" 0.3rem;margin-top: 0px;" id="" value=""/><label style="line-height: 32px;">记住密码</label> <button id="btn">登录</button>
Js代码:
<script type="text/javascript"> //点击记住密码按钮 $(".remember").click(function(){ //如果有值,则将用户名跟密码存入localStorage或者cookie if($(this).prop('checked') && $("#password").val()&& $("#userName").val()){ //localStorage.setItem("password",$("#password").val()); //存入localStorage写法 //localStorage.setItem("userName",$("#userName").val()); $.cookie('password', $("#password").val(), { expires: 7 }); //存入cookie写法(expires:7表示设置有效期为7天) $.cookie('userName', $("#userName").val(), { expires: 7 }); }else{ //localStorage.setItem("password",''); //localStorage.setItem("userName",''); $.cookie("password",'',{ expires: -1 }); $.cookie("userName",'',{ expires: -1 }); } }) $("#btn").click(function(){ if($(".remember").prop('checked') && $("#password").val()&& $("#userName").val()){ //localStorage.setItem("password",$("#password").val()); //localStorage.setItem("userName",$("#userName").val()); // 创建一个cookie并设置有效时间为7天: $.cookie('password', $("#password").val(), { expires: 7 }); $.cookie('userName', $("#userName").val(), { expires: 7 }); console.log($.cookie('password')); }else{ $.cookie('password', '',{ expires: -1 }); //清空cookie里的password $.cookie('userName', '',{ expires: -1 }); //清空cookie里的userName //localStorage.setItem("password",''); //清空localStorage里的password //localStorage.setItem("userName",''); //清空localStorage里的userName } var userName = $("#userName").val(); var password = $("#password").val(); if(!userName){ alertTip("请输入账号!"); } if(!password){ alertTip("请输入密码!"); } $.ajax({ url : basePath + '/login?loginName=' + userName + '&password=' + encodeURIComponent(password), dataType : 'json', type : "post", success : function(data) { if (!data.success) { alertTip(data.errmsg); return; } var userUid=data.user.userUid; toApp(userUid) window.location.href = 'index.html'; }, error : function() { alertTip("未能连接到服务器!"); } }); }) function toApp(userUid){ if (isAndroid()) { //给androidapp传参数 var jsonStr = JSON.stringify({"userUid": userUid}); AppHost.getUserUid(jsonStr); } else { //给ios传参数 window.webkit.messageHandlers.getUserUid.postMessage({"userUid": userUid}); } } </script>
两者区别:
1.cookie的存储大小为4KB,而localStorage的存储数据大小一般都是:5MB
2.cookie若不设置有效时间,则生命周期随浏览器的关闭而结束,若设置了有效时间,则浏览器关闭,cookie数据也在,知道过了有效时间;而localStorage数据,除非你手动清楚,否则会一直存在