$ http响应在angularJS中未定义

时间:2014-08-04 12:35:01

标签: angularjs xmlhttprequest

我遇到了一些问题,我似乎是在回调中获取数据但似乎无法达到它,说实话我并不完全确定发生了什么。

当我点击“获取电影”按钮时,我在控制台中收到以下内容:

Error: response is undefined
app</$scope.addBook@http://onaclovtech.com/apps/movies/:42:1
Wa.prototype.functionCall/<@https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.6/angular.min.js:162:14
Mc[c]</<.compile/</</<@https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.6/angular.min.js:178:390
zd/this.$get</h.prototype.$eval@https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.6/angular.min.js:101:134
zd/this.$get</h.prototype.$apply@https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.6/angular.min.js:101:399
Mc[c]</<.compile/</<@https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.6/angular.min.js:178:370
Xc/c/<@https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.6/angular.min.js:27:145
q@https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.6/angular.min.js:7:357
Xc/c@https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.6/angular.min.js:27:129

按下按钮后,当我查看网络标签时,我得到以下内容:

  

http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=[api-key]&q=The%20Way%20Of%20The%20Gun&page_limit=1&callback=angular.callbacks._0

当我查看调试器时,我得到一个看起来像这样的movies.json响应对象:

angular.callbacks._0(
  {"total":1,"movies":[{"id":"15775","title":"The Way of the Gun","year":2000,"mpaa_rating":"R","runtime":119,"critics_consensus":"","release_dates":{"theater":"2000-09-08","dvd":"2001-06-19"},"ratings":{"critics_rating":"Rotten","critics_score":48,"audience_rating":"Upright","audience_score":71},"synopsis":"","posters":{"thumbnail":"http://content7.flixster.com/movie/11/17/79/11177993_tmb.jpg","profile":"http://content7.flixster.com/movie/11/17/79/11177993_tmb.jpg","detailed":"http://content7.flixster.com/movie/11/17/79/11177993_tmb.jpg","original":"http://content7.flixster.com/movie/11/17/79/11177993_tmb.jpg"},"abridged_cast":[{"name":"Ryan Phillippe","id":"162676004","characters":["Parker"]},{"name":"Benicio Del Toro","id":"162652510","characters":["Longbaugh"]},{"name":"James Caan","id":"162656402","characters":["Joe Sarno"]},{"name":"Juliette Lewis","id":"162654115","characters":["Robin"]},{"name":"Taye Diggs","id":"162655514","characters":["Jeffers"]}],"alternate_ids":{"imdb":"0202677"},"links":{"self":"http://api.rottentomatoes.com/api/public/v1.0/movies/15775.json","alternate":"http://www.rottentomatoes.com/m/way_of_the_gun/","cast":"http://api.rottentomatoes.com/api/public/v1.0/movies/15775/cast.json","reviews":"http://api.rottentomatoes.com/api/public/v1.0/movies/15775/reviews.json","similar":"http://api.rottentomatoes.com/api/public/v1.0/movies/15775/similar.json"}}],"links":{"self":"http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=The+Way+Of+The+Gun&page_limit=1&page=1"},"link_template":"http://api.rottentomatoes.com/api/public/v1.0/movies.json?q={search-term}&page_limit={results-per-page}&page={page-number}"}
)

所以数据似乎都在那里,我只是很难弄清楚如何获得它。

有人可以帮助我指出正确获取数据的方向吗?

(我打算最终将angularjs控制器移动到.js文件,但是现在它在.html文件中,抱歉)

这是我的原始代码:

的index.html

<!DOCTYPE html>
<html ng-app="myapp" manifest="covers.appcache">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.6/angular.min.js"></script>
    <script src="https://cdn.firebase.com/js/client/1.0.11/firebase.js"></script>
    <script src="https://cdn.firebase.com/libs/angularfire/0.7.1/angularfire.min.js"></script>
    <script src="rottentomatoes.js"></script>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <style type="text/css">
    <!--
      /* Move down content because we have a fixed navbar that is 50px tall */
      body {
        padding-top: 50px;
        padding-bottom: 20px;
      }
    -->
    </style>
    <!-- Optional theme -->
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css">
  </head>
  <body ng-controller="MyController">

    <div align="left">
       <button type="button" class="btn btn-primary btn-lg active" ng-click="addBook()">Get Movie</button>
    </div>
    <br />
    <div>
      {{data}}
      {{success}}

    <script>
      var app = angular.module("myapp", ["video"])
      .controller('MyController', ['$scope', '$video', function($scope, $video) {        
        $scope.addBook = function(e) {
          var response = $video.search('[api-key]', 'The Way Of The Gun', '1');

          response
            .success(function(data, status) {console.log('SUCCESS' + data); $scope.data = data;  $scope.status = status;})
            .error(function(data, status) {console.log('ERROR' + status); $scope.data = data; $scope.status = status;});

          // Found somewhere that said I needed a jsonp_callback function, I just tried it to see if it did anything, doesn't appear to
          function jsonp_callback(data) {console.log('JSONP' + data);  $scope.data = data; };
        }    
      }]);

      app.config(function($httpProvider) {
        //Enable cross domain calls
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
        $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
      });
    </script>
  </body>
</html>

rottentomatoes.js

angular.module('video', []).factory('$video', ['$http', function($http) {
  return {
    search: function(api_key, query, page_limit) {
      var method = 'JSONP';
      var url = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?";
      $http({
        method: method,
        url: url + "apikey=" + api_key +
            "&q=" + query +
            "&page_limit=" + page_limit + '&callback=JSON_CALLBACK'
      });
    }
  };
}]);

1 个答案:

答案 0 :(得分:1)

$video.search()方法中,您不返回任何内容,因此发生了错误。

您可以像这样返回$http()来电,它应该有效:

angular.module('video', []).factory('$video', ['$http', function($http) {
  return {
    search: function(api_key, query, page_limit) {
      var method = 'JSONP';
      var url = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?";
      return $http({
        method: method,
        url: url + "apikey=" + api_key +
            "&q=" + query +
            "&page_limit=" + page_limit + '&callback=JSON_CALLBACK'
      });
    }
  };
}]);

作为一般提示:

  • 在调试时使用未经宣传的angular.js代替angular.min.js,它会为您提供更有意义的错误。
  • 无需定义jsonp_callback函数,angular将为您处理
  • 避免使用$前缀$video命名您自己的服务。对于angularjs中内置的任何内容,都会保留$前缀。