請在下面找到我的代碼片段。基本上,用戶從登錄屏幕輸入用戶名和密碼,當用戶點擊它時,我通過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