//测试token
//获取token
function setToken(data){
var storage = window.localStorage;
if(!storage){
alert("浏览器不支持localstorage");
return false;
}
var token = data.access_token;
storage.setItem("user_token", token);
storage.setItem("user_login_time", new Date().getTime());//保存登录时间
}
function getToken()
{
var storage = window.localStorage;
var current = new Date().getTime();//拿token的时间
var token = storage.user_token;//token的值
var old_time = storage.user_login_time;//登录的时间
var time = (current - old_time) /1000;//时间差
var out_time = 3600;// 超时设置
var parse_time = 24 * 60 * 60;// 刷新设置
//手动清除缓存
var length = window.localStorage.length;
if(length==0){
window.location.href = "login.html"
}
//超时
if(parse_time > time && time >= out_time) {
refreshToken(token);
}
//1天过期 重新登录
if(time >= parse_time) {
window.location.href = "login.html";
}
return token;
}
function headerSetup(token)
{
$.ajaxSetup({
'headers':{
'Authorization': 'Bearer '+ token,
}
});
}
//刷新token
function refreshToken(token)
{
if(window.localStorage.length==0){
window.localStorage.clear();
window.location.href = "login.html";
}
$.ajaxSetup({
'headers': {
'Authorization': 'Bearer ' + token,
}
});
$.ajax({
url:"http://ezist.cn/api/authorizations/current",
type:'post',
dataType: "json",
data: {},
success: function(data) {
setToken(data);
},
error: function (data) {
console.log("数据请求失败");
window.location.href='login.html';
}
});
}