我正在尝试根据本地存储中特定 key 的存在来生成 html 内容。代码如下:
// Check if the user is signed in or not
if(localStorage.getItem("token") === null) {
document.getElementById("main").innerHTML = document.getElementById("welcomeview").innerHTML;
} else {
document.getElementById("main").innerHTML = document.getElementById("profileview").innerHTML;
}
即使本地存储中没有设置 token key ,配置文件 View 也会始终显示:
localStorage
Storage { token: "undefined", length: 1 }
为什么?
编辑:
正在使用 AJAX 请求的响应值设置 token :
function sign_in() {
var uri, method, formId, $form, form_data;
uri = location.protocol + '//' + location.host + "/sign_in";
method = "POST";
formId = "#signin_form_id";
$form = $(formId);
form_data = get_form_data($form);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: form_data
};
// Make the request
$.ajax(request).done(function(data) { // Handle the response
// Attributes are retrieved as object.attribute_name
// alert(obj.count);
if(data.successSignIn === false) {
// Login failed we show the welcome page
alert(data.message);
document.getElementById("main").innerHTML = document.getElementById("welcomeview").innerHTML;
} else {
// Login succeeded. We load the user's info, his messages and also a form in which he can type messages
// Save the token received from the server. Could also be stored as a cookie
localStorage.setItem('token', data.token);
// Go to the home page
go_home();
}
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
);
location.reload();
}
最佳答案
已编辑:尝试对设置项localStorage.setItem("token", typeof undefined === data.token ? undefined : data.token)
进行此操作。避免为字符串“undefined”
。
我建议:
1) 替换为 if(localStorage.getItem("token")) {...}
3)此外,您可以通过三元运算符来完成示例
var welcomeText = document.getElementById("welcomeview").innerHTML,
profileText = document.getElementById("profileview").innerHTML;
document.getElementById("main").innerHTML = (localStorage.getItem("token")) ? welcomeText : profileText
关于javascript - Firefox 中本地存储 key 验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32936823/