0

I have multiple pages,

login.html
 -a.html
 -b.html
 .
 .
 -z.html

when user login,I want all this page can get the user information,like user_id and user_name. but without session,how can i do this only in javascript?

2
  • Have you already tried to user browser's cookies to save the user information? Commented Aug 17, 2017 at 1:19
  • You could try localStorage or Cookie Commented Aug 17, 2017 at 1:24

2 Answers 2

1

There are many ways to solve your problem:

Browser's cookies

You can use the browser cookie to get data of a specific domain, like you can see on this W3 school page. One attempt is that you are able to read cookies using your server side

To set a cookie's browser you can do something like this:

var user_name = "John Doe"
var user_id = 1235456
document.cookie = "user_name=" + user_name;
document.cookie = "user_id=" + user_id;

To get the data you can use this function, created on kirlich's answer:

function getCookie(name) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + name + "=");
    if (parts.length == 2) return parts.pop().split(";").shift();
}

getCookie("user_name"); // => John Doe

Local Storage

Local storage has a difference, its can only be read by the client side. Turns your data safe against Cross-site request forgery:

localStorage.setItem("user_name", "John Doe");
localStorage.getItem("user_name"); // => "John Doe"

Session Storage

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.

sessionStorage.username = "John Doe";
console.log(sessionStorage.username); // => "John Doe"
Sign up to request clarification or add additional context in comments.

Comments

0

Use localStorage

var userId = document.getElementById('userId').value;
localStorage.setItem('User Id', userId);

Then on each html page get the User Id with:

var someVariable = localStorage.getItem('User Id');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.