I'm trying to generate html content based on the presence of a specific key in the local storage. The code is as follows:
// 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;
}
The profile view is always shown even though there is no token key set in the local storage:
localStorage
Storage { token: "undefined", length: 1 }
Why?
Edit:
The token is being set with the response value of an AJAX request:
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();
}
Edited: Try this for set item localStorage.setItem("token", typeof undefined === data.token ? undefined : data.token)
. It is avoided to be string "undefined"
.
I suggest that:
1) Replace to if(localStorage.getItem("token")) {...}
3) Also, you can do your example through ternary operator
var welcomeText = document.getElementById("welcomeview").innerHTML,
profileText = document.getElementById("profileview").innerHTML;
document.getElementById("main").innerHTML = (localStorage.getItem("token")) ? welcomeText : profileText
You'd never enter the if
section as "undefined" === null
is always false.
You'd want to check for if(localStorage.getItem("token") === "undefined")
in your case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.