document.addEventListener('DOMContentLoaded', function() {
const profileuserId = window.location.pathname.split('/').slice(-2, -1)[0]; // 주소 URL에 있는 userId를 split을 통해 가져온다.
window.location.pathname.split('/').slice(-2, -1)[0]; :
window.location.pathname = URL이 https://whateversong.com/api/accounts/profile/userId/ 라면,
pathname은 /api/accounts/profile/userId/
.split('/') = '/'를 기준으로 나눈 배열, [' ', 'api', 'accounts', 'profile', 'userId', ' ']
.slice(-2, -1) = 배열을 뒤에서 두 번째부터 첫 번째까지 선택(종료 인덱스 선택 X), ['userId']
[0] = 최종 배열의 첫 번째 인덱스, 'userId'
function loadProfile() {
const access = window.localStorage.getItem('access'); // 저장된 토큰 가져오기
if (!access) {
console.error('No access token found');
return;
}
axios.get(`/api/accounts/api/profile/${profileuserId}/`,{
headers: {
'Authorization': `Bearer ${access}` // 인증 토큰을 헤더에 추가
}
})
.then(response => { // .then 메서드를 통해 비동기적으로 Promise를 반환
const data = response.data;
document.getElementById('username').textContent = data.username;
document.getElementById('email').textContent = data.email;
document.getElementById('nickname').textContent = data.nickname;
if (data.image) {
document.getElementById('profile-picture').src = data.image;
}
loadEditProfileButton()
})
.catch(error => {
console.error('Failed to load profile:', error);
});
};
.then 메서드
- 특징
- Promise 기반의 비동기 작업에서 성공적으로 완료되었을 때 실행할 코드를 지정
- try catch와의 차이점
- 비동기 처리 방식:
- .then: Promise 기반의 비동기 처리 방법으로,
비동기 작업이 완료된 후 실행할 콜백 함수를 지정 - try...catch: async/await와 함께 사용되어 비동기 작업을 동기처럼 작성 가능,
예외 처리가 간편
- .then: Promise 기반의 비동기 처리 방법으로,
- 코드 가독성:
- .then: 중첩된 비동기 작업을 처리할 때 콜백 지옥(callback hell)을 일으킬 수 있음.
- try...catch: async/await와 함께 사용하면 비동기 작업을 동기처럼 작성할 수 있어 가독성이 높아짐
- 오류 처리:
- .then: .catch 메서드를 사용하여 오류를 처리
- try...catch: catch 블록을 사용하여 오류를 처리
- 비동기 처리 방식:
const menuLinks = document.querySelectorAll('.menu a'); // querySelectorAll은 html 요소에서 class 부분을 선택하는 메서드
// 같은 이름의 모든 class를 다 선택한다.
menuLinks.forEach(link => { // .forEach는 menuLinks에 포함된 모든 link들을 반복하여 아래 함수를 실행하는 메서드이다.
link.addEventListener('click', function(event) {
event.preventDefault();
menuLinks.forEach(link => link.classList.remove('active')); // 모든 link에서 active 클래스를 제거
this.classList.add('active'); // this는 이벤트가 발생한 요소를 뜻함, 여기선 클릭된 link 요소에 active 클래스를 추가한다는 의미
});
});
document.getElementById('home-button').addEventListener('click', function() {
window.location.href = '/api/accounts/api/main/'; // 메인 페이지로 이동
});
querySelector
querySelector : 문서 내에서 제공된 선택자(셀렉터)와 일치하는 첫 번째 요소를 반환하는 메서드,
선택자는 CSS 선택자와 동일한 형식으로 작성
querySelectorAll : 문서 내에서 제공된 선택자와 일치하는 모든 요소를 반환하는 메서드,
반환된 요소들은 NodeList 객체에 담겨 있으며, 이는 배열처럼 반복 가능
forEach
배열이나 NodeList와 같은 반복 가능한 객체에 대해 각 요소를 반복하면서
제공된 콜백 함수를 실행하는 메서드
function displayPlaylist(playlists) {
const container = document.getElementById('zzim-playlist-container');
container.innerHTML = ''; // HTML 요소의 내용(content)을 설정하거나 가져오는 속성
playlists.forEach(playlist => {
const item = document.createElement('div');
item.className = 'playlist-item'; // HTML 요소의 클래스 속성을 설정하거나 가져오는 속성
// 이미지 URL이 존재하는지 확인하고 설정
const imageUrl = playlist.image_url || 'https://via.placeholder.com/150';
// 콘솔에 playlist 데이터 전체 출력
console.log(`Playlist Data: ${JSON.stringify(playlist)}`);
// playlist.id를 고유 식별자로 사용
const playlistId = playlist.id;
item.innerHTML = `
<a href="${playlist.link}" target="_blank">
<img src="${imageUrl}" alt="${playlist.name}">
<div class="playlist-info">
<h2>${playlist.name}</h2>
</div>
</a>
<button class="zzim-button" data-id="${playlistId}">♡</button>
`;
container.appendChild(item); // 특정 부모 요소에 새로운 자식 요소를 추가하는 메서드
});
.innerHTML
- 설정할 때: 해당 요소의 모든 기존 내용이 새로운 HTML 문자열로 대체
- 가져올 때: 해당 요소의 HTML 콘텐츠가 문자열로 반환
- container.innerHTML = '';: zzim-playlist-container 요소의 기존 내용을 모두 지움
- item.innerHTML: item 요소의 내부 HTML을 설정하여 플레이리스트 정보를 표시
.className
- 설정할 때: 요소의 기존 클래스 목록이 지정한 클래스 문자열로 대체
- 가져올 때: 요소의 클래스 목록이 문자열로 반환
.appendChild
- 사용할 때: 부모 요소에 새로운 자식 요소를 추가
- container.appendChild(item);: container 요소에 새로 생성한 item 요소를 자식으로 추가
function displayPosts(posts) {
const postList = document.getElementById('post-container');
postList.innerHTML = '';
posts.forEach(post => {
const postElement = document.createElement('div');
let postImage = post.image ? post.image : window.mainLogoImage;
postElement.classList.add('post');
const truncatedContent = post.content.length > 50
? post.content.substring(0, 50) + '...'
: post.content;
postElement.innerHTML = `
<a href=/api/posts/${post.id}/>
<img src=${postImage}>
<div class="content">
<p id="post-title">${post.title}</p>
<p id="post-content">${truncatedContent}</p>
<div class="author-create-like">
<p>${post.category}</p>
<p>${formatDate(post.created_at).toLocaleString()}</p>
<p>좋아요 ${post.like_count}</p>
</div>
</div>
</a>
`;
postList.appendChild(postElement);
});
}
const trancatedContent = post.content.length > 50 ? post.content.substring(0, 50) + '...' : post.content;
? : 조건 ? 참일 때 반환 값 : 거짓일 떄 반환 값
.substring(0, 50) : 문자열의 특정 부분을 추출하는 메서드,
추출을 시작할 위치의 인덱스(0부터 시작),
추출을 종료할 위치의 인덱스 (생략할 경우 문자열의 끝까지 추출)
'JS' 카테고리의 다른 글
Whateversong base.js JS로직 기본 설명 (1) | 2025.03.12 |
---|---|
JWT Token을 이용한 로그인 기능 (0) | 2025.03.12 |