赞
踩
由于chrome等浏览器存在samesite安全措施,导致传统http页面后端无法设置cookie到前端,所以考虑在返回值中添加cookie值,使用前端js进行cookie的设置,获取和删除功能(实现登陆功能)
1.例子中使用了JQuery.js进行get和post请求,同时进行cookie操作
2.password为md5后结果,在一定程度上防止密码泄漏
JS设置cookie
$(document).ready(function(){ $("#btn").click(function(){ // 用text()获取不到数据 var username = $("#username").val(); var password = $("#password").val(); // 获取csrf,提交时加入data var csrfToken = $("[name='csrfmiddlewaretoken']").val(); $.post("/app/log/",{"username": username,"password":password,"csrfmiddlewaretoken":csrfToken},function(data,status){ if(data.error == 0){ // path实现cookie跨域, 若未设置expires则关闭浏览器后cookie失效 var time=new Date() time.setTime(time.getTime()+365*24*60*60*1000) document.cookie="id="+data.id+";path=/;expires="+time.toGMTString(); document.cookie="username="+data.username+";path=/;expires="+time.toGMTString(); document.cookie="password="+data.password+";path=/;expires="+time.toGMTString(); document.cookie="nickname="+data.nickname+";path=/;expires="+time.toGMTString(); //$.cookie('id',data.id,{path:'/'}); // 父页面设置值 parent.$("#lt").html("用户:"+data.nickname+"<br>唯一ID:"+data.id); // 父页面退登按钮显示 parent.$("#u2").css("display","block"); alert('登录成功'); } else { alert(data.text); } }); }); });
JS获取cookie
代码参考:https://www.cnblogs.com/wulibo/p/5955187.html
var id = getCookie("id");
function getCookie(c_name) {
if (document.cookie.length>0) {
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1) {
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}
JS删除cookie
代码参考:https://blog.csdn.net/qq_36470686/article/details/83036534
$("#u2").click(function () {
// 删除cookie
var exp = new Date();
exp.setTime (exp.getTime() - 1);
document.cookie = "id=0; expires="+ exp.toGMTString()+"; path=/";
document.cookie = "username=0; expires="+ exp.toGMTString()+"; path=/";
document.cookie = "password=0; expires="+ exp.toGMTString()+"; path=/";
document.cookie = "nickname=0; expires="+ exp.toGMTString()+"; path=/";
$("#lt").text("未登录");
$("button").css({"color":"white"});
$("#u2").css({"display":"none"});
alert("退登成功");
});
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。