如何在基于MovieDB API的影视项目中仅显示美国电视剧?
解决方案:仅展示美国电视剧(TMDB API)
要解决电视剧板块显示印度剧集的问题,你可以通过两种方式过滤出美国出品的剧集:
方法一:调用API时直接过滤(推荐)
TMDB的/tv/popular接口支持with_origin_country参数,传入美国的国家代码US即可直接获取美国地区的热门剧集,这种方式无需前端额外处理,效率更高。
修改你的API调用代码:
async function displayPopularShows() { // 添加with_origin_country=US参数过滤美国剧集 const { results } = await fetchAPIData('/tv/popular?with_origin_country=US'); results.forEach((show) => { const div = document.createElement('div'); div.classList.add('card'); div.innerHTML = ` <a href="tv-details.html?id=${show.id}"> ${show.poster_path ? `<img src="https://image.tmdb.org/t/p/w500${show.poster_path}" class="card-img-top" alt="${show.name}" />` : `<img src="../images/no-image.jpg" class="card-img-top" alt="${show.name}" />` } </a> <div class="card-body"> <h5 class="card-title">${show.name}</h5> <p class="card-text"> <small class="text-muted">Air Date: ${show.first_air_date}</small> </p> </div> `; document.querySelector('#popular-shows').appendChild(div); }); }
方法二:前端获取结果后过滤
如果无法修改API调用参数,也可以在拿到返回结果后,通过origin_country字段过滤出包含US的剧集:
async function displayPopularShows() { const { results } = await fetchAPIData('/tv/popular'); // 过滤出美国出品的剧集 const usShows = results.filter(show => show.origin_country.includes('US')); usShows.forEach((show) => { const div = document.createElement('div'); div.classList.add('card'); div.innerHTML = ` <a href="tv-details.html?id=${show.id}"> ${show.poster_path ? `<img src="https://image.tmdb.org/t/p/w500${show.poster_path}" class="card-img-top" alt="${show.name}" />` : `<img src="../images/no-image.jpg" class="card-img-top" alt="${show.name}" />` } </a> <div class="card-body"> <h5 class="card-title">${show.name}</h5> <p class="card-text"> <small class="text-muted">Air Date: ${show.first_air_date}</small> </p> </div> `; document.querySelector('#popular-shows').appendChild(div); }); }
说明
默认情况下,/tv/popular会根据API的默认地区或请求的地理位置返回热门剧集,你之前的返回结果偏向印度剧集,大概率是因为API的默认地区设置为印度。通过上述两种方式,都能精准筛选出美国电视剧。
内容的提问来源于stack exchange,提问作者ilkerdemirci
相关产品推荐
相关产品推荐

