I try to create a link by using javascript and I got some errors
<script>
document.addEventListener("DOMContentLoaded", function () {
const token = localStorage.getItem('token'); // Lấy token từ localStorage
const navLinks = document.getElementById('nav-links'); // Lấy phần tử nav chứa các liên kết
const contextPath = window.location.pathname.substring(0, window.location.pathname.indexOf("/", 2)); // Lấy context path
if (token) {
fetch('/api/jwt/getName', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
if (data && data.username) {
const name = data.username; // Assign username from API
console.log(name);
navLinks.innerHTML = '';
// Sử dụng template literals để chèn giá trị `name` từ JavaScript
const profileLinkValue = `<a class="nav-link" href="${contextPath}/profile">${name}</a>`;
// Tạo phần tử `li` chứa liên kết profile
const profileLink = document.createElement('li');
profileLink.classList.add('nav-item');
profileLink.innerHTML = profileLinkValue;
navLinks.appendChild(profileLink);
// Tạo phần tử giỏ hàng và logout
const cartLink = document.createElement('li');
cartLink.classList.add('nav-item');
cartLink.innerHTML = `
<a class="nav-link" href="${contextPath}/shopping_cart">
<img src="/image/shopping-cart.png" alt="Shopping cart" width="35" height="30">
</a>
`;
navLinks.appendChild(cartLink);
const logoutLink = document.createElement('li');
logoutLink.classList.add('nav-item');
logoutLink.innerHTML = `<a class="nav-link" href="${contextPath}/logout">Logout</a>`;
navLinks.appendChild(logoutLink);
}
})
.catch(error => {
console.error('Error fetching user info:', error);
});
}
});
</script>
When I run the web server,the page look like this
enter image description here
The problem here is, the profileLink should show the real account name, not the word ‘name’.
I have tried to log something, and I found the api works fine.
The problem I think is just the jstl variable ${name} in the link.
Could someone tell me the proper syntax for this? Thanks!
Edit : I have hardcored the value of the link as Example Name, and it’s the result
https://drive.google.com/file/d/1Wh1uUq0CMO8ExZv_soqMMsyIjQkwx968/view?usp=sharing
navLinks.innerHTML = `
<li class="nav-item"><a class="nav-link" href="${pageContext.request.contextPath}/profile">ExampleName</a></li>
<li class="nav-item"><a class="nav-link" href="${pageContext.request.contextPath}/shopping_cart">
<img src="/image/shopping-cart.png" alt="Shopping cart" width="35" height="30">
</a></li>
<li class="nav-item"><a class="nav-link" href="${pageContext.request.contextPath}/logout">Logout</a></li>
`;
}
and it showed like the pic above, so I think the real problem is ${data.username}.