我正在尝试使用API从TheMovieDB.org中获取信息,我编写了一个简单的代码来做到这一点,但是当我将click事件添加到按钮/超链接时,它可以工作,然后显示所有NowPlayingMovies。我希望网页现在可以显示正在播放的电影,而无需单击任何按钮。
我尝试使用window.onload
函数并将整个代码放在一个函数中,从而无需单击超链接,但是我无法做到这一点,并且代码无法正常工作并显示各种错误。有人可以帮我解决吗?
window.onload = function updateLatestMovies() {
const xhr = new XMLHttpRequest();
const nowPlayingButton = document.querySelector("#nowPlayingButton");
const endPoint = `https://api.themoviedb.org/3/movie/now_playing?api_key=6a879a78d6083b8f3ba308233e0de85b&language=en-US&page=1`;
xhr.open("GET", endPoint);
xhr.send();
xhr.addEventListener("readystatechange", updateLatestMovies);
const nowPlaying = document.querySelector("#nowPlaying");
if (xhr.readyState == 4) {
const response = JSON.parse(xhr.responseText);
const nowPlayingOutput = document.querySelector("#nowPlaying");
let nowPlayingA = response.results;
let output = "";
for (let i = 0; i < 15; i++) {
output += `
<div id="card">
<a onclick="movieSelected('${nowPlayingA[i].id}')" href="#"><img src="http://image.tmdb.org/t/p/w400/${nowPlayingA[i].poster_path}"></a>
<div class="cardContent">
<a onclick="movieSelected('${nowPlayingA[i].id}')" href="#"><h2>${nowPlayingA[i].title}</h2></a>
<p id="p_rating"><strong>Rating:</strong> <span>${nowPlayingA[i].vote_average} / 10 </span> </p>
<p><strong>Release date:</strong> <span>${nowPlayingA[i].release_date} </span></p>
</div>
</div>`;
}
nowPlayingOutput.innerHTML = output;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Movies Database</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<a href="#nowPlaying" id = "nowPlayingButton" class="btn">See what's on Cinema!</a>
<div id="nowPlaying">
</div>
</body>
</html>
我收到以下错误:
未捕获的TypeError:无法在movie.js:4处读取null的属性'addEventListener'