当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - show data stored in localstorage to another page

问题描述:

I am working with the user authentication in jquery mobile and phonegapp. First i POST the username and password to the server and if success it return some data that are stored in the local-storage.

Here the $ajax post

$.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();

}

});

here the session.js that is setting the localstorage data using JSON.stringify.

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;

}

};

}());

here the O/P of the localstorage

KPSCtuts-session:{"userProfileModel":"Abhilash","userId":"1","userName":"abhilashrajrs","sessionId":"usr_b0424c8b16","expirationDate":"2016-03-23T19:16:16.319Z","keepSignedIn":true}

I want the Name of user to show on another page, how i can pull the data from the local-storage

网友答案:

I think it should work.

var userName = JSON.parse(localStorage.getItem('KPSCtuts-session'))['userName'];

Here, you can use the variable userName.

分享给朋友:
您可能感兴趣的文章:
随机阅读: