Localstorage实现显示未定义的值

时间:2016-12-13 20:07:34

标签: javascript jquery html5 local-storage

请在下面找到我的代码段。基本上,用户从登录屏幕输入用户名和密码,当用户点击它时,我通过Ajax调用传递信息,如果JSON响应包含SUCCESS,如我的检查else if (data_.status == "SUCCESS"){所示,我我计划使用HTML5本地存储。但是,对于以下控制台日志undefined,我得到了console.log("Value check for DEMO.value:"+demo.value); // I saw undefined here,这阻止了我前进。我做错了什么?我正在关注this tutorial

$("#submit").click(function (e) {
     e.preventDefault();
     var userNAME = $("#username").val();
     var passWord = $("#password").val();

     var ajaxRequest = jQuery.ajax({
         data: {
           username: userNAME,
           password: passWord
         },
         dataType: "json",
         method: "POST",
         url: loginUrl
       })
       .done(function (data_, textStatus_, jqXHR_) {
           if (data_.status != "SUCCESS") {
             alert(data_.message);
             return false;

           } else if (data_.status == "SUCCESS") {
             var testedValue = $("#userName").html(userNAME);
             var demoValue = $("#userName").val();
             console.log("Value check for userNAME:" + userNAME);

             // Local Storage Stuff Begins
             // Grab the username
             var demo = document.querySelector('#userName');
             console.log("Value check for demo:" + demo); // I can see the username here

             // localStorage feature detect
             function supportsLocalStorage() {
               return typeof (Storage) !== 'undefined';
             }

             if (!supportsLocalStorage()) {
               // Change the value to inform the user of no support
               demo.value = 'No HTML5 localStorage support, soz.';
             } else {
               console.log("Inside Else Statement; This means the browser has HTML5 localstorage support!"); // I can see this message
               console.log("Value check for DEMO.value:" + demo.value); // I saw undefined here

               // Try this
               try {
                 // Set the interval and autosave every second
                 setInterval(function () {
                   localStorage.setItem('autosave', demo.value);
                 }, 1000);
               } catch (e) {
                 // If any errors, catch and alert the user
                 if (e == QUOTA_EXCEEDED_ERR) {
                   alert('Quota exceeded!');
                 }
               }

               // If there is data available
               if (localStorage.getItem('autosave')) {
                 // Retrieve the item
                 demo.value = localStorage.getItem('autosave');
               }
             } // End of Else
           }
         }
       }
     }
   }
 }

添加HTML以供参考:(我跟着this login dialog

<!-- Login HTML Begins -->
<div id="wrap">
<div id="window" caption="Login">
   <div>
      <table>
         <tr>
            <td>Username:</td>
            <td><input style="width: 150px;" type="text" name="user" id = "username" /></td>
         </tr>
         <tr>
            <td>Password:</td>
            <td><input style="width: 150px;" type="password" name="password" id = "password" /></td>
         </tr>
         <tr>
            <td colspan="2" align="right" valign="bottom">
               <input type="button" id="submit" value="Login" />
            </td>
         </tr>
      </table>
   </div>
</div>
<!-- </div> -->
<!-- Login HTML ends -->

以下HTML标注到我在HTML页面上显示username的位置(不包括完整代码)

<li><a title="Logout" onclick="a" href="#"><i class="fa fa-user whiteIcon"></i>&nbsp;&nbsp;<span id="userName">

3 个答案:

答案 0 :(得分:1)

在制作控制台之前,无法设置demo.value。日志

if (!supportsLocalStorage())

  demo.value = 'No HTML5 localStorage support, soz.';

如果!supportsLocalStorage()为真,则设置如上,但是您以相反的方式将其记录下来。将console.log向下移动到页面下方,然后再进行设置。

答案 1 :(得分:0)

我认为问题在于你使用的是document.querySelector('#userName')而不是document.querySelector('#username')

以下示例显示了它的外观,没有ajax请求:

http://codepen.io/ovitrif/pen/ENdwrj

PS:关于localStorage的逻辑有效。

另一个问题,你正在使用:

var demo = document.querySelector('#username');
console.log("Value check for demo:" + demo);

这意味着您正在尝试将元素本身附加到文本的其余部分。我想你只想要这个值,所以你的代码应该是:

console.log("Value check for demo:" + demo.value);

答案 2 :(得分:0)

你有解决方案使用我所做的一个jQuery Labrary并且正常工作:

// check if browser support storage
    if($.storage())
    {
        // Set a session storage
        $.storage('the_storage', 'the_value');

        // Get session storage
        $.storage('the_storage');

        // delete storage
        $.storage('the_storage', null);
    }
    else
    {
        // browser not support, use cookie
        alert("WARNING!!! Your Browser is old and not have Web Storage support.Perhaps you'll have problems using this site.");
    }

但是我在这个函数中包含了cookie,如果本地存储你的浏览器不支持,自动函数启动使用cookie而你没有问题。

以下是完整的代码功能:GitHub

随意使用它。