简体   繁体   中英

How to retrieve a username from a simple JavaScript login form?

I have a simple javascript login form on the index.html page, if succesful the users is directed to main.html, I would like to display their username in the header on this page. Is it possible to get form the cookies session of through local storage?

  <form name="loginform" onSubmit="return validateForm();" action="main.html" method="post">
      <label>User name</label>
      <input type="text" name="usr" placeholder="username"> 
      <label>Password</label>
      <input type="password" name="pword" placeholder="password">
      <input type="submit" value="Login" class="button"/>
  </form>

  <script>
      function validateForm() {
          var un = document.loginform.usr.value;
          var pw = document.loginform.pword.value;
          var username = "username"; 
          var password = "password";
          if ((un == username) && (pw == password)) {
             return true;
         }
         else {
            alert ("Login was unsuccessful, please check your username and password");
            return false;
         }
      }
  </script>

Main.html

  <script>
    window.onload = function() {
       var name = localStorage.getItem('username');
       if (name != "undefined" || name != "null") {
       document.getElementById('welcomeMessage').innerHTML = "Hello " + name + "!";
       } else
       document.getElementById('welcomeMessage').innerHTML = "Hello!";
    }
   </script>

   <span id="welcomeMessage"></span>

This currently return 'null' as i dont know how to set the localstorage on the index.html

Yes you can set the username:

    window.localStorage.setItem('username',username);

Then access it on any page:

   window.localStorage.getItem('username');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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