请在下面找到我的代码片段。基本上,用户从登录屏幕输入用户名和密码,当用户点击它时,我通过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 belogs到我显示HTML页面上的username
(全码的位置)
<li><a title="Logout" onclick="a" href="#"><i class="fa fa-user whiteIcon"></i> <span id="userName">
尝试使用demo.text() – CognitiveDesire
为什么不使用变量'demoValue'而不是'demo.value'? – vbguyny
@vbguyny我遵循教程中提到的相同模式。 – John