[英]Get the same value in multiple pages using javascript
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. 当用户登录时,我希望所有页面都能获取用户信息,例如user_id和user_name。 but without session,how can i do this only in javascript?
但没有会话,我该如何仅使用javascript?
There are many ways to solve your problem:
有很多方法可以解决您的问题:
You can use the browser cookie to get data of a specific domain, like you can see on this W3 school page . 您可以使用浏览器cookie获取特定域的数据,就像在W3学校页面上看到的那样。 One attempt is that you are able to read cookies using your server side
一种尝试是您能够使用服务器端读取Cookie
To set a cookie's browser you can do something like this: 要设置Cookie的浏览器,您可以执行以下操作:
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 : 要获取数据,您可以使用在kirlich的答案上创建的此函数:
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 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"
The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. sessionStorage对象与localStorage对象相同,只不过它仅存储一个会话的数据。 The data is deleted when the user closes the specific browser tab.
当用户关闭特定的浏览器选项卡时,数据将被删除。
sessionStorage.username = "John Doe";
console.log(sessionStorage.username); // => "John Doe"
Use localStorage
使用
localStorage
var userId = document.getElementById('userId').value;
localStorage.setItem('User Id', userId);
Then on each html page get the User Id with: 然后在每个html页面上获取具有以下内容的用户ID:
var someVariable = localStorage.getItem('User Id');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.