gpt4 book ai didi

javascript - OMDb API 无法在 JavaScript 中运行

转载 作者:行者123 更新时间:2023-11-28 05:57:07 24 4
gpt4 key购买 nike

我正在使用OMDb API获取电影的标题、年份和运行时间。这些应该在页面加载后立即出现在页面上。我为此使用了 j query ajax。但它不起作用。

页面加载后,它就会显示未定义的内容。我哪里出错了??

我是 j query ajax 和 API 的新手,因此我们将不胜感激。提前致谢:)

<! doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">< </script>

<script type="text/javascript">

window.onload=function()
{
$.ajax({
url: "http://www.omdbapi.com/?t=spiderman&y=&plot=full&r=json",
crossDomain: true,
dataType: "json",
success: fetch
});
}
//For fetching data on success
function fetch(e){
var result="";
$.each(e,function(value){

result+="<p>" +value.Title +"</p>";
result+="<p>" +value.Year +"</p>";
result+="<p>" +value.Runtime +"</p>";

});
$('#movie').html(result); //For storing result in html
}
</script>

</head>

<body>
<p id="movie"></p>

</body>

最佳答案

为了从对象中获取所有返回值,您需要通过键和值获取每个属性,返回的 json 如下所示:

{"Title":"Spiderman","Year":"1990","Rated":"N/A","Released":"N/A","Runtime":"5 min","Genre":"Short","Director":"Christian Davi","Writer":"N/A","Actors":"N/A","Plot":"N/A","Language":"German","Country":"Switzerland","Awards":"N/A","Poster":"N/A","Metascore":"N/A","imdbRating":"5.7","imdbVotes":"90","imdbID":"tt0100669","Type":"movie","Response":"True"}

因此只需调用 e.Title 即可获取标题或使用 $.each 以键和值作为参数循环进入对象。第一个参数是属性名称(KEY),第二个参数是值。

$.each(e,function(key,value){
result+="<p>"+ key + " : " + value +"</p>";
});

<! doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">< </script>

<script type="text/javascript">

window.onload=function()
{
$.ajax({
url: "http://www.omdbapi.com/?t=spiderman&y=&plot=full&r=json",
crossDomain: true,
dataType: "json",
success: fetch
});
}
//For fetching data on success
function fetch(e){
var result="";
//where keys are attribute names and values are their values
$.each(e,function(key,value){
result+="<p>"+ key + " : " + value +"</p>";

});

$('#movie').html(result); //For storing result in html
}
</script>

</head>

<body>
<p id="movie"></p>

</body>

关于javascript - OMDb API 无法在 JavaScript 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37571313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com