我正在尝试使用 AJAX 调用从网络上的电影 API 检索数据。这是我的 HTML 代码:
<html>
<head>
<meta charset=utf-8>
<title>Movie Database</title>
</head>
<body onload = "loadMyData(), loadYear()">
<div id = "main-content">
<h1>Movie Database</h1>
<select id="genre" class="filterButton">
</select>
<select id="releaseDate" class="filterButton">
</select>
<input type="text" value="Enter Release Date YYYY-MM-DD">
<button id="search">SEARCH</button>
</div>
<div id = "content"></div>
<script src = "myScript4.js"></script>
</body>
</html>
这是我的 JS 文件:
/* THIS IS THE JS FILE FOR THE www.themoviedb.org WEBSITE API */
// MY GLOBAL VARIABLES
var title;
var genre;
var releaseYear;
var summary;
var actors;
var languages; // What languges is the movie in?
var status; // Is this movie releases or still in production?
/* ======================= HERE ARE MY EVENT LISTENERS ==================*/
var myList = document.getElementById("getList");
var myYear = document.getElementById("getRelease");
var getGenre = document.getElementById("genre");
var getYear = document.getElementById("releaseDate");
/* ======================= End of my Event Listeners =================== */
/* =========This is the function to display the data in the HTML ======= */
function displayData(results, title, poster_path, overview)
{
var div = document.createElement('div');
div.setAttribute('results', Results);
div.innerHTML = Title + '<br />' + Poster + Overview;
document.body.appendChild(div);
}
/* ============================ End function ========================= */
/* ============This is how the data from the genre is loaded ========== */
function loadMyData() {
var data = "{}";
var xhr = new XMLHttpRequest();
xhr.withCredentials = false;
console.log(xhr);
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
//console.log(this.responseText);
var sourceData = JSON.parse(xhr.responseText);
console.log(sourceData);
displayData(results, title, poster_path, overview);
var source = document.getElementById("genre");
for (var i = 0; i < sourceData.genres.length; i++) {
console.log(i);
optionID = sourceData.genres[i].id;
var optionName = sourceData.genres[i].name;
var option = document.createElement("option");
option.innerHTML = optionName;
option.setAttribute("value", optionID);
option.setAttribute("name", optionName);
source.appendChild(option);
//displayData(results, title, poster_path, overview);
//console.log(optionName);
}
}
});
xhr.open("GET", "https://api.themoviedb.org/3/genre/movie/list?language=en-US&api_key=**************");
xhr.send(data);
}
// loads the year from the Discover part of the API
function loadYear() {
var data = "{}";
var newxhr = new XMLHttpRequest();
newxhr.withCredentials = false;
console.log(newxhr);
newxhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
var sourceData = JSON.parse(newxhr.responseText);
//console.log(sourceData);
var source = document.getElementById("releaseDate");
for (var i = 0; i < sourceData.results.length; i++) {
console.log(i);
optionID = sourceData.results[i].id;
var optionName = sourceData.results[i].release_date;
var option = document.createElement("option");
option.innerHTML = optionName;
option.setAttribute("value", optionID);
option.setAttribute("name", optionName);
source.appendChild(option);
console.log(optionName);
}
}
});
newxhr.open("GET", "https://api.themoviedb.org/3/discover/movie?page=1&include_video=false&include_adult=false&sort_by=popularity.desc&language=en-US&api_key=*****************");
newxhr.send(data);
}
/* --------------------------------------------- On click show the data ------------------------------------------------ */
document.getElementById("search").addEventListener("click", displayData);
LoadMyData() 加载该类型的数据。我想我应该重新命名它。 LoadYear() 当然会加载电影的日期。
DisplayData() 应该在用户单击按钮后显示 JSON 文件中的数据。
有人可以告诉我如何使用纯 JavaScript 和 html 来显示 JSON 数据吗?现在我收到一条错误消息:
myScript4.js:55 Uncaught ReferenceError: 结果未定义 在 XMLHttpRequest 处。 (myScript4.js:55)
第 55 行在这里:displayData(results, title, poster_path,overview);
任何帮助将不胜感激:)出于安全原因我也摆脱了 API key 。我知道你不应该把它们送人。
以下是 loadYear() 函数输出的 JSON 文件的片段:
{
"page": 1,
"total_results": 328130,
"total_pages": 16407,
"results": [
{
"vote_count": 2039,
"id": 346364,
"video": false,
"vote_average": 7.4,
"title": "It",
"popularity": 745.88068,
"poster_path": "/9E2y5Q7WlCVNEhP5GiVTjhEhx1o.jpg",
"original_language": "en",
"original_title": "It",
"genre_ids": [
12,
18,
27
],
"backdrop_path": "/tcheoA2nPATCm2vvXw2hVQoaEFD.jpg",
"adult": false,
"overview": "In a small town in Maine, seven children known as The Losers Club come face to face with life problems, bullies and a monster that takes the shape of a clown called Pennywise.",
"release_date": "2017-09-05"
},
如您所见,“结果”位于 JSON 文件中。这是 JavaScript 文件中未定义的位。我该如何定义它?
最佳答案
这部分代码:
var sourceData = JSON.parse(xhr.responseText);
console.log(sourceData);
displayData(results, title, poster_path, overview);
“结果”尚未定义。我不知道您期望“结果”在哪里或是什么,但我猜测它只是 responseText 的 json 中的一个对象,因此您应该在 displayData 调用之前添加此行:
var results = sourceData.results;
如果 results
不是 sourceData
的属性,那么显然需要 var results
> 等于响应中您需要的任何内容。
关于javascript - 如何使用 Vanilla JavaScript 将来自此 API 的数据显示为 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46727458/