简体   繁体   中英

How do I get the data from API using Javascript and Ajax?

When I write something in the input and then press search I want to get the title from movies that has that word in it, how do I do that? Im using the omdb API. Here is my code right now.

 document.getElementById("getForm").addEventListener("submit", loadMovies); function loadMovies() { var omdbAPI = new XMLHttpRequest(); var omdbURL = "http://www.omdbapi.com/?t=the%20revenant&type=movie"; omdbAPI.open("get", omdbURL, true); omdbAPI.onload = function(event) { event.preventDefault(); if(this.status == 200) { var result = JSON.parse(this.responseText); console.log(result); var output = ""; for(var i in result) { output += '<div class="user">' + '<h3>Titel: '+result.Title+'</h3>' + '</div>'; } document.getElementById('result').innerHTML = output; } else { alert("No results"); } } omdbAPI.send(); }
 <form action="" method="get" id="getForm"> Movie: <input type="text" name="query"> <button type="submit">Search</button> </form> <div id="result"> </div>

You aren't getting any results because OMDB requires an API key and you aren't providing one. When sending a proper GET request you receive the following response: {"Response":"False","Error":"No API key provided."} .

You are also reloading the page by allowing the default form submission action to occur, instead use event.preventDefault() to cancel the page reload from occurring when form submission occurs, then calling your function. I modified your function to include a name parameter to search with. The below should accomplish what you want, but since you don't have an API key you will still not get any results. Go here , to get an API key.

 document.getElementById("getForm").addEventListener("submit", (e) => { e.preventDefault(); loadMovies(document.querySelector("input[name='query']").value); }); function loadMovies(name) { var omdbAPI = new XMLHttpRequest(); var omdbURL = `http://www.omdbapi.com/?t=${name.replace(" ", "%20")}&type=movie`; omdbAPI.open("get", omdbURL, true); omdbAPI.onload = function(event) { event.preventDefault(); if (this.status == 200) { var result = JSON.parse(this.responseText); console.log(result); var output = ""; for (var i in result) { output += '<div class="user">' + '<h3>Titel: ' + result.Title + '</h3>' + '</div>'; } document.getElementById('result').innerHTML = output; } else { alert("No results"); } } omdbAPI.send(); }
 <form action="" method="get" id="getForm"> Movie: <input type="text" name="query"> <button type="submit">Search</button> </form> <div id="result"> </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