使用 JavaScript 获取 IMDB 信息

Get IMDB info using JavaScript

我正在尝试使用 JavaScript 获取 IMDB 信息。以下代码适用于 Title、Year、IMDB link,但是当我尝试获取“Runtime”、“Director”、“Released”等时,我得到的是未定义的。请帮忙!

这是数据格式:https://www.omdbapi.com/?i=tt4779682&apikey=ba1f4581

代码:

var data;
function getanswer(q){
$.get("https://www.omdbapi.com/?s="+q+"&apikey=ba1f4581", function(rawdata){
var rawstring =JSON.stringify(rawdata);
data =JSON.parse(rawstring);
var title = data.Search[0].Title;
var year = data.Search[0].Year; 
var director = data.Search[0].Director; 
var imdburl="https://www.imdb.com/title/"+data.Search[0].imdbID+"/";

var posterurl =data.Search[0].Poster;
document.getElementById('answer').innerHTML="<h1>"+title+"</h1><br> <img src= '"+posterurl+"'><br><p> Year Released:"+year+"</p> <br><p> Year Released:"+director+"</p> <br> <p> IMDB page: <a href='"+imdburl+"'target='_blank'>"+imdburl+"</a></p>"; }); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<html>
<head></head>
<body onload="getanswer(document.getElementById('querybox').value)">
<!doctype html> <input value="The Meg" onkeyup="getanswer(document.getElementById('querybox').value)" id="querybox"> <div id="answer"></div> 
</body>
</html>

根据 api 文档,您使用的 s 参数不会 return Runtime/Director/etc。您可以使用 t 参数并删除 Search[0].

下面是可行的代码:

var data;
function getanswer(q){
$.get("https://www.omdbapi.com/?t="+q+"&apikey=ba1f4581", function(rawdata){
var rawstring =JSON.stringify(rawdata);
data =JSON.parse(rawstring);
console.log(data);
var title = data.Title;
var year = data.Year; 
var director = data.Director; 
var imdburl="https://www.imdb.com/title/"+data.imdbID+"/";

var posterurl =data.Poster;
document.getElementById('answer').innerHTML="<h1>"+title+"</h1><br> <img src= '"+posterurl+"'><br><p> Year Released:"+year+"</p> <br><p> Year Released:"+director+"</p> <br> <p> IMDB page: <a href='"+imdburl+"'target='_blank'>"+imdburl+"</a></p>"; }); }