You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

学校电影信息网站项目:使用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

  1. Wrong API Response Path: The error occurs because response.data.with_genres doesn't exist! Looking at the TMDB API response you shared, the list of movies lives in the results array—with_genres is just a parameter you sent in the request, not a field in the response.
  2. 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/w500 to get a usable image URL (you can swap w500 for other sizes like w300 or original based on your layout needs).
  • Targeted Wrapper Selection: Used #find-genres instead of .wrapper to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 08:02:44