jQuery发送json请求+保存coockie案例

前端登录实现与Cookie管理
该博客详细介绍了前端登录功能的实现,包括用户名和密码的验证,使用JSON.stringify处理请求参数,以及AJAX进行POST请求到指定API。同时,文章还涉及到Cookie的设置与获取,包括设置和删除Cookie的函数实现,确保用户登录状态的维护。
$("#submit").click(function () {
  let userName = $("#userName").val();
  let password = $("#password").val();

  if (!userName) {
    alert("用户名不能为空");
    return;
  }
  if (!password) {
    alert("密码不能为空");
    return;
  }

  let param = { userName: userName, password: password };
  param = JSON.stringify(param);
  console.log(param);
  $.ajax({
    type: "POST",
    url: "http://127.0.0.1:8080/api/login",
    datatype: "json",
    headers: {
      "content-type": "application/json;charset=utf-8",
      token: getCookie("token"),
    },
    async: false,
    data: param,
    success: function (res) {
      console.log(res);
      if (res.code == "1") {
        // 保存cookie
        SetCookie("token", res.data.token);
        SetCookie("userinfo", res.data);
        console.log(res);
      } else {
        alert(res.msg);
      }
    },
    error: function (err) {
      console.log(err);
    },
  });
});

//写cookies函数
function SetCookie(name, value) {
  //两个参数,一个是cookie的名子,一个是值
  var Days = 7; //此 cookie 将被保存 7 天
  var exp = new Date(); //new Date("December 31, 9998");
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
  document.cookie =
    name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}
function getCookie(name) {
  //取cookies函数
  var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
  if (arr != null) return unescape(arr[2]);
  return null;
}
function delCookie(name) {
  //删除cookie
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval = getCookie(name);
  if (cval != null)
    document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhopq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值