OMDb API无法在javascript中运行

时间:2016-06-01 14:17:51

标签: javascript jquery api

我正在使用OMDb API来获取电影的标题,年份和运行时间。这些应该在加载后立即显示在页面上。我使用了j查询ajax。但它不起作用。

一旦页面加载,它就会显示未定义的内容。我在哪里弄错了?

我是j新查询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>

1 个答案:

答案 0 :(得分:0)

为了从对象获取所有返回的值,您需要按键和值获取每个属性,返回的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"}

所以只需使用带键和值作为参数的$ .each调用e.Title获取标题或循环到对象。 第一个参数是属性名称(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>