我正在使用jquery mobile和phonegapp中的用户身份验证。首先,我将用户名和密码POST到服务器,如果成功,它将返回存储在本地存储中的一些数据。
这里是$ ajax帖子
$.ajax({
type: 'POST',
dataType: "json",
url: KPSCtuts.Settings.Url,
data:"username=" + userName + "&password=" + password + "&login=",
success: function (resp) {
$.mobile.loading("hide");
if (resp.success === true) {
// Create session.
var today = new Date();
var expirationDate = new Date();
expirationDate.setTime(today.getTime() + KPSCtuts.Settings.sessionTimeoutInMSec);
KPSCtuts.Session.getInstance().set({
userProfileModel: resp.userProfileModel,
userId: resp.userId,
userName: resp.userName,
sessionId: resp.sessionId,
expirationDate: expirationDate,
keepSignedIn:me.$chkKeepSignedIn.is(":checked")
});
// Go to main menu.
$.mobile.navigate(me.mainMenuPageId);
return;
} else {
if (resp.extras.msg) {
me.$ctnErr.html("<p>"+resp.extras.msg+"</p>");
me.$ctnErr.addClass("bi-ctn-err").slideDown();
}
}
},
error: function (e) {
$.mobile.loading("hide");
console.log(e.message);
// TODO: Use a friendlier error message below.
me.$ctnErr.html("<p>1-Oops! KPSCtuts had a problem and could not log you on. Please try again in a few minutes.</p>");
me.$ctnErr.addClass("bi-ctn-err").slideDown();
}
});
这里是使用JSON.stringify设置localstorage数据的session.js。
var KPSCtuts = KPSCtuts || {};
KPSCtuts.Session = (function () {
var instance;
function init() {
var sessionIdKey = "KPSCtuts-session";
return {
// Public methods and variables.
set: function (sessionData) {
window.localStorage.setItem(sessionIdKey, JSON.stringify(sessionData));
},
get: function () {
var result = null;
try {
result = JSON.parse(window.localStorage.getItem(sessionIdKey));
} catch(e){}
return result;
}
};
};
return {
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
}
};
}());
这里是localstorage的O / P
KPSCtuts-session:{"userProfileModel":"Abhilash","userId":"1","userName":"abhilashrajrs","sessionId":"usr_b0424c8b16","expirationDate":"2016-03-23T19:16:16.319Z","keepSignedIn":true}
我希望用户名显示在另一个页面上,我如何从本地存储中提取数据
答案 0 :(得分:1)
我认为它应该有用。
var userName = JSON.parse(localStorage.getItem('KPSCtuts-session'))['userName'];
在这里,您可以使用变量userName。