我正在学习使用API。我正在尝试在OMDb API中搜索电影标题,然后在我的网站上显示电影图像/海报。我不能让这个代码工作,并希望知道我哪里出错了。先感谢您。
// Creating the AJAX Request
//
$('form').submit(function(event) {
// Stop the form from submitting
event.preventDefault();
// Get The value from the form
var movieURL = "http://www.omdbapi.com/?";
var movieName = $('#search').val();
var movieOptions = {
s: "",
};
function displayMovies(data) {
var movieHTML = '<ul>';
$.each(data.items, function(index, value) {
movieHTML += '<li>';
movieHTML += '<img ';
movieHTML += 'src="' + value.Poster + '" ';
movieHTML += 'alt="' + value.Title + '" >';
movieHTML += '</li>';
});//end each
movieHTML += '</ul>';
$('movieInformation').html(movieHTML);
}
$.getJSON(movieURL, movieOptions, displayMovies);// end getJSON
}); // end submit function
<div class="heading">
<h1>Movie Search</h1>
<form>
<label for="search">Type a movie title</label>
<input type="search" name="search" id="search">
<input type="submit" value="Search" id="submit">
</form>
</div>
<div id="movieInformation">
</div>
答案 0 :(得分:1)
我注意到的一些事情:
根据API, movieURL
不是正确构造的URL。您发送的请求不包含搜索值。你有:
"http://www.omdbapi.com/?"
代替:
"https://www.omdbapi.com/?t="+movieName
响应是一个对象,不包含'items`属性:
$.each(data.items, function(index, value) {
我创建了一个小提琴,记录了您的回复内容data
。您将确切地看到您可以访问的属性。
https://jsfiddle.net/um69o5t3/1/
更新
以下是我改变的内容:
$('form').submit(function(event) {
// Stop the form from submitting
event.preventDefault();
// Get The value from the form
var movieName = $('#search').val();
var movieURL = "https://www.omdbapi.com/?t="+movieName;
var movieOptions = {
s: "",
};
function displayMovies(data) {
console.log(data);
/* var movieHTML = '<ul>';
$.each(data.items, function(index, value) {
movieHTML += '<li>';
movieHTML += '<img ';
movieHTML += 'src="' + value.Poster + '" ';
movieHTML += 'alt="' + value.Title + '" >';
movieHTML += '</li>';
});//end each*/
console.log(data.Title);
var movieHTML = '<ul>';
movieHTML += '<li>';
movieHTML += '<img ';
movieHTML += 'src="' + data.Poster + '" ';
movieHTML += 'alt="' + data.Title + '" >';
movieHTML += '</li>';
movieHTML += '</ul>';
$('#movieInformation').html(movieHTML);
}
$.getJSON(movieURL, movieOptions, displayMovies);// end getJSON
}); // end submit function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="heading">
<h1>Movie Search</h1>
<form>
<label for="search">Type a movie title</label>
<input type="search" name="search" id="search">
<input type="submit" value="Search" id="submit">
</form>
</div>
<div id="movieInformation">
</div>