使用angularJS和Rotten Tomato进行API调用

时间:2014-02-14 00:19:35

标签: javascript angularjs rotten-tomatoes

现在我只是想让API调用工作,没什么特别的。最后,我只想要一些基本的信息,比如姓名,运行时,评级和描述......但这都是后来的事。我甚至无法让API调用工作。

我做了几个教程,我似乎错过了一些东西。

HTML          

<head>
<title>Watch a movie!</title>

<meta charset = "UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta name="description" content="">
<meta name="keywords" content="">

<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.0rc1/angular-route.min.js"></script>
<script src="controllers/movies.js"></script>

</head>
<body>
<div id="wrapper">
<button type="button" class="btn btn-primary btn-lg btn-block">NOW PLAYING</button>
<button type="button" class="btn btn-default btn-lg btn-block">COMING FRIDAY</button>

<!-- PLACEHOLDER -->
<div id="movieInfoBox">
<div ng-controller = "movieController">{{movies}}</div>
</div>

</div> <!-- END WRAPPER -->

JS

var movies = angular.module("movies", []); //quotes are name of this file
movies.controller("movieController", function ($scope, $http){ //quotes are name of function called in index

     $http.jsonp("http://api.rottentomatoes.com/api/public/v1.0/movies/155655062.json?apikey=wq98h8vn4nfnuc3rt2293vru")

     .sucess(function(data)
          {$scope.movies = data;})
     .error(function(data){});
 });

1 个答案:

答案 0 :(得分:4)

您必须在URL中包含JSON_CALLBACK。否则,API将返回JSON而不是JSONP。在下面的代码中,我直接在查询字符串中使用配置对象而不是参数。这只是因为它更容易阅读,您还可以使用您的版本并向URL添加&amp; callback = JSON_CALLBACK。请参阅'jsonp'in the docs

工作小提琴:http://jsfiddle.net/pascalockert/fM7jb/

控制器中的代码:

$http.jsonp('http://api.rottentomatoes.com/api/public/v1.0/movies/155655062.json', {
    params: {
        apikey: 'wq98h8vn4nfnuc3rt2293vru',
        callback: 'JSON_CALLBACK'
    }
})
.success(function (data) {
    $scope.movies = data;
});