Html获取登陆用户名的示例代码
The method for retrieving the logged-in username in HTML depends on the specific implementation of the login system and whether it stores the username in the browser or on the server-side. Here are two common scenarios:
1. Retrieving Username from Client-Side Storage:
If the username is stored in client-side storage (e.g., localStorage or sessionStorage), you can retrieve it using JavaScript:
JavaScript
// Retrieve username from localStorage
const storedUsername = localStorage.getItem('username');
if (storedUsername) {
console.log('Logged in user:', storedUsername);
} else {
console.log('Not logged in');
}
2. Retrieving Username from Server-Side:
If the username is stored on the server-side, you may need to make an AJAX request to the server to retrieve it. This typically involves sending a request to a server-side script that checks the user's authentication status and returns the username if they are logged in.
JavaScript
// Make an AJAX request to retrieve username
fetch('/getUsername', {
method: 'GET',
headers: {
'Authorization': 'Bearer <your_auth_token>', // Replace with actual auth token
}
})
.then(response => response.json())
.then(data => {
if (data.username) {
console.log('Logged in user:', data.username);
} else {
console.log('Not logged in');
}
});
Considerations: