TMDB API 데이터 불러오기(fetch)
1. 영화 데이터를 가져올 수 있는 API를 제공하는 TMDB
2. API data fetch를 할 수 있는 코드를 받는다.
홈페이지 - 프로필 수정 - API - API 키 요청 - 문서로 이동 - 상단 tab의 API reference - 왼쪽 tab에서 원하는 데이터 묶음 선택 - fetch code 에서 try it! 누르기 - 그러면 response code 나옴
3. vscode script.js
fetch code 복사 및 붙여넣기 -> 그 아래에 response code 복사 붙여넣기 -> 코드 속 오류 고치기(아래 빨간 부분)
코드 보기 (아래 클릭)
const options = {
method: 'GET',
headers: {
accept: 'application/json',
Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIzZjI5M2EzNGQ5YTdhYmE3ZmE2YjA1MmVkNDBhNzAzNSIsInN1YiI6IjY1MmY3YTM2MDI0ZWM4MDEwMTU0MzQ3NCIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.4UlNrO-aIaz-15g60eboaP-Zr-ck8iYXpu1qfhKZm0E'
}
};
fetch('https://api.themoviedb.org/3/tv/top_rated?language=en-US&page=1', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
{
"page": 1, // => "page"; 1,
"results": [ // => "results";
{
"backdrop_path": "/7BzmK4MWc0cj4hCxwWURt6TS6UR.jpg",
"first_air_date": "2023-08-31",
"genre_ids": [
16,
10765,
10759,
35
],
"id": 131378,
"name": "Adventure Time: Fionna & Cake",
"origin_country": [
"US"
],
"original_language": "en",
"original_name": "Adventure Time: Fionna & Cake",
"overview": "Fionna and Cake – with the help of the former Ice King, Simon Petrikov - embark on a multiverse-hopping adventure and journey of self-discovery. All the while a powerful new antagonist determined to track them down and erase them from existence, lurks in the shadows.",
"popularity": 165.657,
"poster_path": "/fi1b6U1kp73xheECzqwzMn8u3mX.jpg",
"vote_average": 9.3,
"vote_count": 115
},
{
"backdrop_path": "/9faGSFi5jam6pDWGNd0p8JcJgXQ.jpg",
"first_air_date": "2008-01-20",
"genre_ids": [
18,
80
],
"id": 1396,
"name": "Breaking Bad",
"origin_country": [
"US"
],
"original_language": "en",
"original_name": "Breaking Bad",
"overview": "When Walter White, a New Mexico chemistry teacher, is diagnosed with Stage III cancer and given a prognosis of only two years left to live. He becomes filled with a sense of fearlessness and an unrelenting desire to secure his family's financial future at any cost as he enters the dangerous world of drugs and crime.",
"popularity": 258.379,
"poster_path": "/3xnWaLQjelJDDF7LT1WBo6f4BRe.jpg",
"vote_average": 8.9,
"vote_count": 12469
},
{
"backdrop_path": "/rkB4LyZHo1NHXFEDHl9vSD9r1lI.jpg",
"first_air_date": "2021-11-06",
"genre_ids": [
16,
18,
10765,
10759
],
"id": 94605,
"name": "Arcane",
"origin_country": [
"US"
],
"original_language": "en",
"original_name": "Arcane",
"overview": "Amid the stark discord of twin cities Piltover and Zaun, two sisters fight on rival sides of a war between magic technologies and clashing convictions.",
"popularity": 52.942,
"poster_path": "/fqldf2t8ztc9aiwn3k6mlX3tvRT.jpg",
"vote_average": 8.7,
"vote_count": 3357
},
{
"backdrop_path": "/4Mt7WHox67uJ1yErwTBFcV8KWgG.jpg",
"first_air_date": "1999-10-20",
"genre_ids": [
10759,
35,
16
],
"id": 37854,
"name": "One Piece",
"origin_country": [
"JP"
],
"original_language": "ja",
"original_name": "ワンピース",
"overview": "Years ago, the fearsome Pirate King, Gol D. Roger was executed leaving a huge pile of treasure and the famous \"One Piece\" behind. Whoever claims the \"One Piece\" will be named the new King of the Pirates.\n\nMonkey D. Luffy, a boy who consumed a \"Devil Fruit,\" decides to follow in the footsteps of his idol, the pirate Shanks, and find the One Piece. It helps, of course, that his body has the properties of rubber and that he's surrounded by a bevy of skilled fighters and thieves to help him along the way.\n\nLuffy will do anything to get the One Piece and become King of the Pirates!",
"popularity": 110.435,
"poster_path": "/fcXdJlbSdUEeMSJFsXKsznGwwok.jpg",
"vote_average": 8.7,
"vote_count": 4089
},
{
"backdrop_path": "/8CXw90lEmnJQeUvkgSnl5bEjbQI.jpg",
"first_air_date": "2013-12-02",
"genre_ids": [
16,
35,
10765,
10759
],
"id": 60625,
"name": "Rick and Morty",
"origin_country": [
"US"
],
"original_language": "en",
"original_name": "Rick and Morty",
"overview": "Rick is a mentally-unbalanced but scientifically gifted old man who has recently reconnected with his family. He spends most of his time involving his young grandson Morty in dangerous, outlandish adventures throughout space and alternate universes. Compounded with Morty's already unstable family life, these events cause Morty much distress at home and school.",
"popularity": 936.13,
"poster_path": "/gdIrmf2DdY5mgN6ycVP0XlzKzbE.jpg",
"vote_average": 8.7,
"vote_count": 8643
},
{
"backdrop_path": "/A6tMQAo6t6eRFCPhsrShmxZLqFB.jpg",
"first_air_date": "2009-04-05",
"genre_ids": [
10759,
16,
10765
],
"id": 31911,
"name": "Fullmetal Alchemist: Brotherhood",
"origin_country": [
"JP"
],
"original_language": "ja",
"original_name": "鋼の錬金術師 FULLMETAL ALCHEMIST",
"overview": "Edward and Alphonse Elric's reckless disregard for alchemy's fundamental laws ripped half of Ed's limbs from his body and left Al's soul clinging to a cold suit of armor. To restore what was lost, the brothers scour a war-torn land for the Philosopher's Stone, a fabled relic which grants the ability to perform alchemy in impossible ways.\n\nThe Elrics are not alone in their search; the corrupt State Military is also eager to harness the artifact's power. So too are the strange Homunculi and their shadowy creator. The mythical gem lures exotic alchemists from distant kingdoms, scarring some deeply enough to inspire murder. As the Elrics find their course altered by these enemies and allies, their purpose remains unchanged – and their bond unbreakable.",
"popularity": 83.721,
"poster_path": "/5ZFUEOULaVml7pQuXxhpR2SmVUw.jpg",
"vote_average": 8.7,
"vote_count": 1757
},
{
"backdrop_path": "/70YdbMELM4b8x8VXjlubymb2bQ0.jpg",
"first_air_date": "2017-03-19",
"genre_ids": [
18,
10751
],
"id": 70785,
"name": "Anne with an E",
"origin_country": [
"CA"
],
"original_language": "en",
"original_name": "Anne with an E",
"overview": "A coming-of-age story about an outsider who, against all odds and numerous challenges, fights for love and acceptance and for her place in the world. The series centers on a young orphaned girl in the late 1890’s, who, after an abusive childhood spent in orphanages and the homes of strangers, is mistakenly sent to live with an elderly woman and her aging brother. Over time, 13-year-old Anne will transform their lives and eventually the small town in which they live with her unique spirit, fierce intellect and brilliant imagination.",
"popularity": 74.871,
"poster_path": "/6P6tXhjT5tK3qOXzxF9OMLlG7iz.jpg",
"vote_average": 8.7,
"vote_count": 4390
},
{
"backdrop_path": "/kU98MbVVgi72wzceyrEbClZmMFe.jpg",
"first_air_date": "2005-02-21",
"genre_ids": [
16,
10759,
10765
],
"id": 246,
"name": "Avatar: The Last Airbender",
"origin_country": [
"US"
],
"original_language": "en",
"original_name": "Avatar: The Last Airbender",
"overview": "In a war-torn world of elemental magic, a young boy reawakens to undertake a dangerous mystic quest to fulfill his destiny as the Avatar, and bring peace to the world.",
"popularity": 47.808,
"poster_path": "/cHFZA8Tlv03nKTGXhLOYOLtqoSm.jpg",
"vote_average": 8.7,
"vote_count": 3508
},
{
"backdrop_path": "/nTvM4mhqNlHIvUkI1gVnW6XP7GG.jpg",
"first_air_date": "2019-04-06",
"genre_ids": [
16,
10759,
10765
],
"id": 85937,
"name": "Demon Slayer: Kimetsu no Yaiba",
"origin_country": [
"JP"
],
"original_language": "ja",
"original_name": "鬼滅の刃",
"overview": "It is the Taisho Period in Japan. Tanjiro, a kindhearted boy who sells charcoal for a living, finds his family slaughtered by a demon. To make matters worse, his younger sister Nezuko, the sole survivor, has been transformed into a demon herself. Though devastated by this grim reality, Tanjiro resolves to become a “demon slayer” so that he can turn his sister back into a human, and kill the demon that massacred his family.",
"popularity": 72.337,
"poster_path": "/xUfRZu2mi8jH6SzQEJGP6tjBuYj.jpg",
"vote_average": 8.7,
"vote_count": 5645
},
{
"backdrop_path": "/6UH52Fmau8RPsMAbQbjwN3wJSCj.jpg",
"first_air_date": "2021-03-25",
"genre_ids": [
16,
10765,
10759,
18
],
"id": 95557,
"name": "Invincible",
"origin_country": [
"US"
],
"original_language": "en",
"original_name": "Invincible",
"overview": "Mark Grayson is a normal teenager except for the fact that his father is the most powerful superhero on the planet. Shortly after his seventeenth birthday, Mark begins to develop powers of his own and enters into his father’s tutelage.",
"popularity": 139.968,
"poster_path": "/lxVS24ZhG3WQf3IMbkFIg6olT6A.jpg",
"vote_average": 8.7,
"vote_count": 3731
},
{
"backdrop_path": "/hMjvf1xGcCbbobFuM2iYR9Tj0Yr.jpg",
"first_air_date": "2022-04-22",
"genre_ids": [
18
],
"id": 124834,
"name": "Heartstopper",
"origin_country": [
"GB"
],
"original_language": "en",
"original_name": "Heartstopper",
"overview": "Teens Charlie and Nick discover their unlikely friendship might be something more as they navigate school and young love in this coming-of-age series.",
"popularity": 59.263,
"poster_path": "/p0AtD0ivSlHq2MHY6JFgyhNqAQY.jpg",
"vote_average": 8.7,
"vote_count": 1055
},
{
"backdrop_path": "/jsXKG9uppnPrhqFNhImllyCfLhl.jpg",
"first_air_date": "2016-04-03",
"genre_ids": [
10759,
16
],
"id": 65930,
"name": "My Hero Academia",
"origin_country": [
"JP"
],
"original_language": "ja",
"original_name": "僕のヒーローアカデミア",
"overview": "Izuku has dreamt of being a hero all his life—a lofty goal for anyone, but especially challenging for a kid with no superpowers. That’s right, in a world where eighty percent of the population has some kind of super-powered “quirk,” Izuku was unlucky enough to be born completely normal. But that’s not enough to stop him from enrolling in one of the world’s most prestigious hero academies.",
"popularity": 41.19,
"poster_path": "/ivOLM47yJt90P19RH1NvJrAJz9F.jpg",
"vote_average": 8.7,
"vote_count": 4519
},
{
"backdrop_path": "/uoA7xBzCt3XXqL5fMmB8pmYgABJ.jpg",
"first_air_date": "2016-12-02",
"genre_ids": [
18,
10765,
35
],
"id": 67915,
"name": "Goblin",
"origin_country": [
"KR"
],
"original_language": "ko",
"original_name": "쓸쓸하고 찬란하神-도깨비",
"overview": "In his quest for a bride to break his immortal curse, a 939-year-old guardian of souls meets a grim reaper and a sprightly student with a tragic past.",
"popularity": 69.423,
"poster_path": "/sPkxHNw5BFvuCFGWw825TS7n6X3.jpg",
"vote_average": 8.7,
"vote_count": 2548
},
{
"backdrop_path": "/uDgy6hyPd82kOHh6I95FLtLnj6p.jpg",
"first_air_date": "2023-01-15",
"genre_ids": [
18
],
"id": 100088,
"name": "The Last of Us",
"origin_country": [
"US"
],
"original_language": "en",
"original_name": "The Last of Us",
"overview": "Twenty years after modern civilization has been destroyed, Joel, a hardened survivor, is hired to smuggle Ellie, a 14-year-old girl, out of an oppressive quarantine zone. What starts as a small job soon becomes a brutal, heartbreaking journey, as they both must traverse the United States and depend on each other for survival.",
"popularity": 154.064,
"poster_path": "/uKvVjHNqB5VmOrdxqAt2F7J78ED.jpg",
"vote_average": 8.7,
"vote_count": 4110
},
{
"backdrop_path": "/rqbCbjB19amtOtFQbb3K2lgm2zv.jpg",
"first_air_date": "2013-04-07",
"genre_ids": [
10765,
16,
10759
],
"id": 1429,
"name": "Attack on Titan",
"origin_country": [
"JP"
],
"original_language": "ja",
"original_name": "進撃の巨人",
"overview": "Several hundred years ago, humans were nearly exterminated by Titans. Titans are typically several stories tall, seem to have no intelligence, devour human beings and, worst of all, seem to do it for the pleasure rather than as a food source. A small percentage of humanity survived by walling themselves in a city protected by extremely high walls, even taller than the biggest Titans. Flash forward to the present and the city has not seen a Titan in over 100 years. Teenage boy Eren and his foster sister Mikasa witness something horrific as the city walls are destroyed by a Colossal Titan that appears out of thin air. As the smaller Titans flood the city, the two kids watch in horror as their mother is eaten alive. Eren vows that he will murder every single Titan and take revenge for all of mankind.",
"popularity": 60.664,
"poster_path": "/8C5gYahMFmzHKGNID8QrG5t25WU.jpg",
"vote_average": 8.7,
"vote_count": 5520
},
{
"backdrop_path": "/2vbE9ajftJ7dkqUAyxDS0WFILx8.jpg",
"first_air_date": "2010-09-06",
"genre_ids": [
16,
35
],
"id": 31132,
"name": "Regular Show",
"origin_country": [
"US"
],
"original_language": "en",
"original_name": "Regular Show",
"overview": "Two bored groundskeepers, Mordecai (a six-foot-tall blue jay) and Rigby (a hyperactive raccoon) are best friends who spend their days trying to entertain themselves by any means necessary, much to the displeasure of their boss. Their everyday pursuits often lead to things spiraling out of control and into the surreal.",
"popularity": 177.18,
"poster_path": "/mS5SLxMYcKfUxA0utBSR5MOAWWr.jpg",
"vote_average": 8.7,
"vote_count": 1788
},
{
"backdrop_path": "/cHyY5z4txdVyGtYMvBJhCqCcJso.jpg",
"first_air_date": "2020-01-10",
"genre_ids": [
16,
10765,
18,
10759,
35
],
"id": 92685,
"name": "The Owl House",
"origin_country": [
"US"
],
"original_language": "en",
"original_name": "The Owl House",
"overview": "An animated fantasy-comedy series that follows Luz, a self-assured teenage girl who accidentally stumbles upon a portal to a magical world where she befriends a rebellious witch, Eda, and an adorably tiny warrior, King. Despite not having magical abilities, Luz pursues her dream of becoming a witch by serving as Eda's apprentice at the Owl House and ultimately finds a new family in an unlikely setting.",
"popularity": 122.591,
"poster_path": "/zhdy3PcNVE15wj1wrxn45ARZBnx.jpg",
"vote_average": 8.7,
"vote_count": 1385
},
{
"backdrop_path": "/900tHlUYUkp7Ol04XFSoAaEIXcT.jpg",
"first_air_date": "2019-05-06",
"genre_ids": [
18
],
"id": 87108,
"name": "Chernobyl",
"origin_country": [
"US"
],
"original_language": "en",
"original_name": "Chernobyl",
"overview": "The true story of one of the worst man-made catastrophes in history: the catastrophic nuclear accident at Chernobyl. A tale of the brave men and women who sacrificed to save Europe from unimaginable disaster.",
"popularity": 48.243,
"poster_path": "/hlLXt2tOPT6RRnjiUmoxyG1LTFi.jpg",
"vote_average": 8.7,
"vote_count": 5402
},
{
"backdrop_path": "/5jtc5va1gDiRi9pjnGqgCN1W0hF.jpg",
"first_air_date": "2006-07-09",
"genre_ids": [
16,
35,
18
],
"id": 42821,
"name": "Welcome to the N.H.K.",
"origin_country": [
"JP"
],
"original_language": "ja",
"original_name": "NHKにようこそ!",
"overview": "Sato's life – or what's left of it – is a paranoid mess of conspiracy theories and social anxieties. He's terrified of the outside world; his apartment is overflowing with the remnants of cheap take-out food; and his retinas have been permanently scarred by a steady diet of internet porn. But maybe it's not all his fault. After all, the nefarious N.H.K. is out there, and they’re determined to turn society's fringe-dwellers into a brainwashed lot of jobless, hopeless, futureless recluses.\n\nEnter Misaki – a mysterious girl-next-door type who is Sato's last chance to beat-down his inner demons and venture out into the light of day. She's ready to help him overcome his crippling phobias, but Sato would rather cower in his existential foxhole and pretend to work on the demo for his virtual sex game.\n\nHe’s afraid to face the world. She's strangely desperate to fix a total stranger. Maybe together they can be normal.",
"popularity": 13.172,
"poster_path": "/hIsRcWso57zxD2MWBSqze5G4NDS.jpg",
"vote_average": 8.6,
"vote_count": 104
},
{
"backdrop_path": "/hPea3Qy5Gd6z4kJLUruBbwAH8Rm.jpg",
"first_air_date": "2015-02-08",
"genre_ids": [
80,
18
],
"id": 60059,
"name": "Better Call Saul",
"origin_country": [
"US"
],
"original_language": "en",
"original_name": "Better Call Saul",
"overview": "Six years before Saul Goodman meets Walter White. We meet him when the man who will become Saul Goodman is known as Jimmy McGill, a small-time lawyer searching for his destiny, and, more immediately, hustling to make ends meet. Working alongside, and, often, against Jimmy, is “fixer” Mike Ehrmantraut. The series tracks Jimmy’s transformation into Saul Goodman, the man who puts “criminal” in “criminal lawyer\".",
"popularity": 124.064,
"poster_path": "/fC2HDm5t0kHl7mTm7jxMR31b7by.jpg",
"vote_average": 8.6,
"vote_count": 4393
}
],
"total_pages": 153, // => "total_pages"; 153,
"total_results": 3045 // => "total_results"; 3045
}
________________
코드를 위에서부터 분석해보자.
// --------------TMDB API Request ----------------- //
const options = {
method: 'GET',
headers: {
accept: 'application/json',
Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIzZjI5M2EzNGQ5YTdhYmE3ZmE2YjA1MmVkNDBhNzAzNSIsInN1YiI6IjY1MmY3YTM2MDI0ZWM4MDEwMTU0MzQ3NCIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.4UlNrO-aIaz-15g60eboaP-Zr-ck8iYXpu1qfhKZm0E'
}
};
fetch('https://api.themoviedb.org/3/tv/top_rated?language=en-US&page=1', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err)); // err(에러)가 났을 때는 실행중지하고 error을 출력해라
// --------------TMDB API Response (임의로 써놓은 것임 : 축약형) ----------------- //
// 영화 정보(results 부분)가 객체 형태(JSON)로 들어가있는 배열의 형태를 띈다.
// JSON 이란? JavaScript 객체 리터럴, 배열, 스칼라 데이터를 표현하는 텍스트 기반의 방식
// {page: 1, results: Array(20), total_pages: 153, total_results: 3045} //
// 대충 이런 형태로 이루어져 있다.
// --------------TMDB API Response (원본형) ----------------- //
{
"page"; 1, // page 정보
"results"; [ // result data 는 [ { "keyname" : "value", "keyname" : [ 배열 value ] } ] 형태로 묶여있다.
{
"backdrop_path": "/7BzmK4MWc0cj4hCxwWURt6TS6UR.jpg",
"first_air_date": "2023-08-31",
"genre_ids": [
16,
10765,
10759,
35
],
"id": 131378,
"name": "Adventure Time: Fionna & Cake",
"origin_country": [
"US"
],
"original_language": "en",
"original_name": "Adventure Time: Fionna & Cake",
"overview": "Fionna and Cake – with the help of the former Ice King, Simon Petrikov - embark on a multiverse-hopping adventure and journey of self-discovery. All the while a powerful new antagonist determined to track them down and erase them from existence, lurks in the shadows.",
"popularity": 165.657,
"poster_path": "/fi1b6U1kp73xheECzqwzMn8u3mX.jpg",
"vote_average": 9.3,
"vote_count": 115
},
________________
4. API data 잘 가져왔는지, 결과보기
Chrome 개발자 도구의 console 을 켜면 results 의 array(배열) 총 20개가 불러와져 있다는 것을 확인할 수 있다.
불러온 TMDB API 데이터 화면에 띄우기
이제..fetch 부분 code 서부터 코드를 붙이면 된다.
1. 기본 개념 알기
먼저 fetch 와 함께 있는 메소드 필수 지식이 필요하다 (아래 클릭!)
fetch('https://api.themoviedb.org/3/tv/top_rated?language=en-US&page=1', options) // fetch 라는 함수명을 가진 함수 안에 인자로 api data에 접근할 수 있는 key가 되는 url 주소와, options 가 들어간다 //
.then(response => response.json()) // 비동기 작업의 동기적 표현: Promise
.then(response => console.log(response))
.catch(err => console.error(err));
fetch() => 늘 promise를 반환하기 때문에 then 체이닝으로 엮을 수 있다
json() => 얘도 promise를 반환한다
2. 그럼 어디다가 함수를 붙여넣어야 받아온 데이터를 사용할 수 있을까?
두번째 then 메소드 안에 써주면 된다.
fetch('https://api.themoviedb.org/3/tv/top_rated?language=en-US&page=1', options) //API Data url을 통해
.then(response => response.json()) // 약속이 이행되면 response 를 response 안에 json 형태로 데이터를 가져오기
.then(response => console.log(response)) // 가져온 데이터를 아래처럼 실행하기 (적용)
.catch(err => console.error(err));
(1) fetch의 첫번째 인자 input 이 너무 길어 변수에 담아주기
const API_url = "https://api.themoviedb.org/3/movie/top_rated?language=en-US&page=1"; // url이 길기때문에 변수안에 넣어줌
(2) 데이터를 보여줄 함수도 내용이 길어질 수 있으니 변수에 담아주기
function fetchSecondThen(data) { 이제 여기다가 코드를 써볼까? }
fetch(API_url, options) // API Data url을 통해
.then(response => response.json()) // 약속이 이행되면 response 를 response 안에 json 형태로 데이터를 가져오기
.then(data => fetchSecondThen(data)) // 가져온 데이터를 아래처럼 실행하기 (적용)
.catch(err => console.error(err));
3. 데이터를 웹사이트 화면에 보이게 하기 + 영화카드 클릭시 id 값 alert 뜨게 하기
const IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500/";
const movieCard = document.querySelector(".movieCard");
const movieImage = document.querySelector(".movieImage");
// --------------TMDB API: API request and get ----------------- //
const options = {
method: 'GET',
headers: {
accept: 'application/json',
Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIzZjI5M2EzNGQ5YTdhYmE3ZmE2YjA1MmVkNDBhNzAzNSIsInN1YiI6IjY1MmY3YTM2MDI0ZWM4MDEwMTU0MzQ3NCIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.4UlNrO-aIaz-15g60eboaP-Zr-ck8iYXpu1qfhKZm0E'
}
};
const API_url = "https://api.themoviedb.org/3/movie/top_rated?language=en-US&page=1"; // url이 길기때문에 변수안에 넣어줌
function fetchSecondThen(data) {
// ---------- 초기 세팅 ----------- //
let dataIndex = data['results']; // 우리가 앞으로 쓸 영화데이터 = 데이터(data)의 안에 있는 results 값 :result는 [ { "keyname" : "value", "keyname" : [ 배열 value ] } ] 형태로 묶여있다.
// ----------- 영화데이터 보여주기 ----------- //
const cardList = document.querySelector('.list_area'); // 받아온 데이터를 넣어줄 공간
cardList.innerHTML = ""; // 받아온 데이터를 넣어줄 공간 안에 html 내용 초기화
dataIndex.forEach((i) => { //
let myTitle = i['title']; // i[key 값] = i.key
let myOverView = i['overview'];
let myPosterPath = i['poster_path'];
let myVoteAverage = i['vote_average'];
let myId = i['id'];
// html에 넣어지는 tag + 콘텐츠
let temp_html = `
<div data-id="${myId}" class="movieCard" >
<img class="movieImage" src="${IMAGE_BASE_URL}${myPosterPath}" alt="">
<div class="movieName">
<h3>${myTitle}</h3>
<p class="movieGrade">Rating : ${myVoteAverage}</p>
</div>
<p class="movieExplanation">${myOverView}</p>
</div>`;
cardList.insertAdjacentHTML('beforeend', temp_html); // temp_html을 데이터 넣어줄 공간안에서 마지막 자식 이후에 위치시키기
});
// ------------- 영화 카드 클릭시 ID 보여주기 ----------- //
const movieIdShowbyClick = function () {
const movieCards = document.querySelectorAll(".movieCard"); // 영화카드 모두 찾아 선택
movieCards.forEach(card => { // 영화카드들의 배열을 한번씩 모두 함수에 대입
card.addEventListener("click", function () { // "이벤트명", 함수 이하의 동작을 하는 이벤트 등록
let movieCardId = this.getAttribute("data-id"); // 영화카드클래스 안에 속성 data-id 값
alert(`영화 ID : ${movieCardId}`); // 영화 data id 값 alert
})
})
}
movieIdShowbyClick(); // 실행
}
내가 쓴 문법들
insertAdjacentHTML()
Array.prototype.forEach()
addEventListener
element.getAttribute()
(참고블로그)
'부트캠프 개발일지 2023-2024 > Bootcamp 생활기록' 카테고리의 다른 글
[3주차] JavaScript 개인과제: 검색기능 (TMDB API 데이터), 홈화면으로가기, 마우스이벤트 (0) | 2023.10.20 |
---|---|
[3주차] Promise( ), fetch( ), then( ), async( ), await( ), mouseover (0) | 2023.10.19 |
[3주차] 알고리즘 특강 (2) (0) | 2023.10.17 |
[3주차] 알고리즘 특강 (1) (0) | 2023.10.16 |
[2주차] KPT : 미니프로젝트 회고 (0) | 2023.10.12 |