学校电影信息网站项目:使用TMDB API实现分类按钮功能时JavaScript代码报错求助
Fixing Your TMDB Genre Movie Display Bug
Hey Francisco, let's sort out that JavaScript error you're hitting with your movie genre display feature. Here's what's going wrong and how to fix it:
Key Issues in Your Current Code
- Wrong API Response Path: The error occurs because
response.data.with_genresdoesn't exist! Looking at the TMDB API response you shared, the list of movies lives in theresultsarray—with_genresis just a parameter you sent in the request, not a field in the response. - Broken HTML Rendering Logic: Your current code tries to replace a placeholder that doesn't exist (
#find-genres) using the wrapper's outer HTML, which won't generate the movie cards you need to display content.
Corrected JavaScript Code
function getFindGenres() { const wrapper = document.querySelector('#find-genres'); wrapper.innerHTML = ""; // Clear existing content first axios({ method: 'get', url: 'https://api.themoviedb.org/3/discover/movie?api_key=YOUR_API_KEY&page=1&with_genres=28' // Replace YOUR_API_KEY with your actual TMDB key }) .then(function (response) { // Iterate over the results array (where the movie data is stored) response.data.results.forEach(movie => { // Create HTML for each movie card const movieCard = ` <div class="movie-card"> <img src="https://image.tmdb.org/t/p/w500${movie.poster_path}" alt="${movie.title}" /> <h4>${movie.title}</h4> <p>Rating: ${movie.vote_average}</p> <p class="release-date">Released: ${movie.release_date}</p> </div> `; // Append the movie card to the target wrapper wrapper.insertAdjacentHTML('beforeend', movieCard); }); }) .catch(function(error) { // Add error handling to debug issues like invalid keys or network problems console.error('Error fetching movies:', error); }); }
Key Explainers & Improvements
- TMDB Image URL Fix: TMDB returns partial poster paths, so we prepend
https://image.tmdb.org/t/p/w500to get a usable image URL (you can swapw500for other sizes likew300ororiginalbased on your layout needs). - Targeted Wrapper Selection: Used
#find-genresinstead of.wrapperto ensure we're modifying the exact container in your HTML, avoiding accidental changes to other elements with the same class. - Error Handling: Added a
.catch()block to log API request failures—this will save you time debugging issues like expired API keys or network outages. - Cleaner HTML Generation: Built each movie card as a template literal, making the code easier to read and modify compared to string replacement hacks.
Optional: Dynamic Genre Button Setup
If you want to load different genres when clicking buttons, modify the function to accept a genre ID parameter:
function getMoviesByGenre(genreId) { const wrapper = document.querySelector('#find-genres'); wrapper.innerHTML = ""; axios({ method: 'get', url: `https://api.themoviedb.org/3/discover/movie?api_key=YOUR_API_KEY&page=1&with_genres=${genreId}` }) .then(function (response) { response.data.results.forEach(movie => { const movieCard = ` <div class="movie-card"> <img src="https://image.tmdb.org/t/p/w500${movie.poster_path}" alt="${movie.title}" /> <h4>${movie.title}</h4> <p>Rating: ${movie.vote_average}</p> </div> `; wrapper.insertAdjacentHTML('beforeend', movieCard); }); }) .catch(function(error) { console.error('Error fetching movies:', error); }); } // Example: Attach to a button click // document.getElementById('action-btn').addEventListener('click', () => getMoviesByGenre(28));
Then add genre buttons in your HTML and link them to this function with the correct genre ID (you can get all genre IDs from the TMDB genre list API endpoint).
内容的提问来源于stack exchange,提问作者Francisco Lemos
相关产品推荐
相关产品推荐

