js实现登录页面保存用户名密码的cookie实例
有客户要求反复登录每次输入用户名密码很麻烦,可用js保存cookie,直接上实例代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <head> <script> function setCookie(cname,cvalue,exdays){ var d = new Date(); d.setTime(d.getTime()+(exdays*24*60*60*1000)); var expires = "expires="+d.toGMTString(); document.cookie = cname+"="+cvalue+"; "+expires; } function getCookie(cname){ var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i].trim(); if (c.indexOf(name)==0) { return c.substring(name.length,c.length); } } return ""; } function saveCookie(){//登录页面保存前 保存cookie var user=$("#username").val(); var password=$("#password").val(); setCookie("username",user,365); setCookie("password",password,365);//365天有效 } $(function() {// 初始化加载cookie var user=getCookie("username"); var password=getCookie("password"); if (user!=""){ $("#username").val(user);//给页面用户名赋值 } if (password!=""){ $("#password").val(password);//给页面密码赋值 } }); </script> </head> <body onload="checkCookie()"> <form action="${root!}/tour/do_login" method="post" onsubmit="return saveCookie()"> <table > <tr> <td><label id="zh">帐号:</label></td> <td colspan="3"><input id="username" type="text"/></td> </tr> <tr> <td><label id="zh">密码:</label></td> <td colspan="3"><input id="password" type="password" name="password" /></td> </tr> </table> <div class="centera"> <input value="登 录" onclick="checkCookie()" type="submit"> </div> </form> </body> </html>
本文原创,转载必追究版权。