简体   繁体   中英

How do I display the Data from this API using Vanilla JavaScript into the HTML?

I am trying to use an AJAX call to retrieve data from a movie API on the web. Here is my HTML code:

<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>

Here is my JS file:

/* 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() loads the data for the genre. I suppose I should rename it. LoadYear() of course loads the date of the movie.

DisplayData() is supposed to display the data from the JSON file once the user clicks the button.

Can someone please give me an idea as to how to use plain javascript and html to show the JSON data? Right now I get an error telling me this:

myScript4.js:55 Uncaught ReferenceError: results is not defined at XMLHttpRequest. (myScript4.js:55)

Line 55 is here: displayData(results, title, poster_path, overview);

Any help would be appreciated :) I've also gotten rid of the API Key for security reasons. I know you're not supposed to give them away.

Here is a snippet of the outputted JSON file for the loadYear() function:

{
  "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"
    },

As you can see "results" is in the JSON file. This is the bit that was undefined in the JavaScript file. How do I define it?

At this part of the code:

var sourceData = JSON.parse(xhr.responseText);
console.log(sourceData);
displayData(results, title, poster_path, overview);

'results' is not yet defined. I don't know where or what you expect 'results' to be, but I'm going to make a guess that it's just an object inside the json of responseText, so you should add this line before your displayData call:

var results = sourceData.results; If results is not a property of sourceData then obviously make var results equal to whatever, in the response, you need it to be.

Javascript is case a sensitive language

so your displayData function seems to have some incorrect variables, should be like this:

function displayData(results, title, poster_path, overview)
{
  var div = document.createElement('div');
  div.setAttribute('results', results);
  div.innerHTML = title + '<br />' + poster_path + overview;
  document.body.appendChild(div);   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM