用cookie保存用户的登录信息,规定保存的期限

时间:2022-10-01 07:45:07

html:

        <form action="#" method="get" id="mycookie">
          <table border="0" cellspacing="0" cellpadding="0">
            <tbody>
              <tr height="50" valign="top">
                <td width="55">&nbsp;</td>
                <td>
                  <span class="fl" style="font-size:24px;">登录</span>
                  <span class="fr">还没有商城账号,<a href="Regist.html" style="color:#ff4e00;">立即注册</a></span>
                </td>
              </tr>
              <tr height="70">
                <td>用户名</td>
                <td><input id="name" type="text" value="" class="l_user"></td>
              </tr>
              <tr height="70">
                <td>密&nbsp; &nbsp; 码</td>
                <td><input id="pasw" type="password" value="" class="l_pwd"></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td style="font-size:12px; padding-top:20px;">
                  <span style="font-family:'宋体';" class="fl">
                    <label class="r_rad"><input id="chkSave" type="checkbox"></label><label
                      class="r_txt">请保存我这次的登录信息</label>
                  </span>
                  <span class="fr"><a href="javascript:void(0)" style="color:#ff4e00;">忘记密码</a></span>
                </td>
              </tr>
              <tr height="60">
                <td>&nbsp;</td>
                <td><input type="submit" value="登录" class="log_btn"></td>
              </tr>
            </tbody>
          </table>
        </form>

javascript:

    $(function () {
            //保存客户的登录信息
            if ($.cookie("name") && $.cookie("pasw")) {
              //取值如果存在则赋值 
              $("#name").val($.cookie("name"));
              $("#pasw").val($.cookie("pasw"))
            }
            $("#mycookie").submit(function () {
              //如果选中了保存用户名选项 
              if ($("#chkSave").is(":checked")) {
                //设置Cookie值 
                $.cookie("name", $("#name").val(), {
                  expires: 7,//设置保存期限  7天
                  path: "/"//设置保存的路径 
                });
                $.cookie("pasw", $("#pasw").val(), {
                  expires: 7,//设置保存期限  7天
                  path: "/"//设置保存的路径 
                });
                alert("存了cookie");
              }
              else {
                //销毁对象 
                $.cookie("name", null, {
                  path: "/"
                });
                $.cookie("pasw", null, {
                  path: "/"
                });
                alert("销毁了cookie");
              }
         
              return false;
            });
          })

4.备注: cookie只有在启动服务器项目下,才能进行正常存取操作。