JavaScript sessionStorage不在页面之间保持...但有时只是

时间:2017-10-20 23:14:39

标签: javascript html

我有两个页面,每个页面都有一个链接到另一个页面的表单。两者都将事务提交到sessionStorage,然后重定向到最后一页。

createaccount.html - 工作正常

<script>
  function submitAccount() {
    try {
      var username = $("input[type=text][name=Username").val();
      var state = $("select[name=State]").val();
      var city = $("input[type=text][name=City]").val();
      var school = $("input[type=text][name=School]").val();

      var locale = {
        state: state,
        city: city,
        school: school
      };

      database.ref('users/' + username).set(locale);

      sessionStorage.setItem('state', state);
      sessionStorage.setItem('city', city);
      sessionStorage.setItem('school', school);

      return true;
    } catch (e) {
      console.log(e);
      return false;
    }
  }
</script>
<form action="viewevents.html" method="get" onsubmit="return submitAccount();" style="text-align:left;color:teal;display:inline-block;">
  <!-- form contents -->
</form>

login.html - 无法正常工作

<script>
  function submitLogin() {
    try {
      var username = $("input[type=text][name=Username]").val();

      database.ref('users/' + username).once('value', function(snap) {

        sessionStorage.setItem('state', snap.val().state);
        sessionStorage.setItem('city', snap.val().city);
        sessionStorage.setItem('school', snap.val().school);

        console.log(sessionStorage.getItem('state'));  // these show up fine, so they must be getting cleared on the redirect
        console.log(sessionStorage.getItem('city'));
        console.log(sessionStorage.getItem('school'));
      });
      return true;
    } catch (e) {
      console.log(e);
      return false;
    }
  }
</script>
<form action="viewevents.html" method="get" onsubmit="return submitAccount();" style="text-align:left;color:teal;display:inline-block;">
  <!-- form contents -->
</form>

viewevents.html

<script>
  var state = sessionStorage.getItem('state');
  var city = sessionStorage.getItem('city');
  var school = sessionStorage.getItem('school');
</script>

奇怪的是,createaccount.html完美运行。当login.html重定向时,sessionStorage变量会消失(即使他们正在获取console.log&#39; ed)。甚至更奇怪 - 如果我修改submitLogin()函数以返回false,那么它不会重定向,然后在提交表单后手动导航到viewevents.html它可以正常工作。不知何故,当浏览器自动重定向sessionStorage时,消失了。

有人可以解释一下发生了什么吗?

0 个答案:

没有答案