简体   繁体   English

从本地存储到 HTML 页面的显示名称

[英]display name from local Storage to HTML page

I want my html page will display "WELCOME" and the user name from local storage.我希望我的 html 页面将显示“欢迎”和本地存储中的用户名。 I have the name in local storage but I don't know how to display it in HTML page我在本地存储中有名称,但我不知道如何在 HTML 页面中显示它

js file: .js 文件:

//register
function store(){
    event.preventDefault();
    var name = document.getElementById('name').value;
    var pw = document.getElementById('pw').value;
    ...
    const user = { name: name, pw: pw};
    const userObjectString = JSON.stringify(user);
    localStorage.setItem(name, userObjectString);
    window.location = "./user.html";
    alert('Your account has been created');
  }
 //login
 function check(){
        event.preventDefault();
        var userName = document.getElementById('userName').value;
        var userPw = document.getElementById('userPw').value;
        var userObjectString = window.localStorage.getItem(userName);
        if (!userObjectString && userName != "gk" && userPw != "123") {
            alert('Error on login');
        } else {
            var user = JSON.parse(userObjectString);
            if(userName == user.name && userPw == user.pw){
                alert('You are logged in.');
                window.location = "./user.html";
            } else {
                alert('Error on login');
            }
         }
       }

You need quotes in the localStorage key AND use textContent to stop possibly XSS:您需要 localStorage 键中的引号并使用 textContent 来阻止可能的 XSS:

localStorage.setItem("name", userObjectString); 

then you can do那么你可以做

const obj = JSON.parse(localStorage.getItem("name") || \`{}\`);
if (obj && obj.name) document.querySelector("h1").textContent += obj.name;

assuming you have假设你有

<h1>Welcome</h1>

Note you may want to sanitize the name before saving it请注意,您可能需要在保存名称之前对其进行清理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM