使用 Angular.js获取 JSONP

Fetching JSONP with Angular.js

本文关键字:JSONP 获取 js Angular 使用      更新时间:2023-09-26
<html ng-app="movieApp">
 <head>
 <meta charset="utf-8">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
 <script>
  var base = 'http://api.themoviedb.org/3';
  var service = '/movie/862';
  var apiKey = '####';
  var callback = 'JSON_CALLBACK';
  var url = base + service + '?api_key=' + apiKey + '&callback=' + callback;
  var movieApp = angular.module('movieApp', []);
  movieApp.controller('MovieCtrl', function ($scope, $http){
      $http.jsonp(url).then(function(data) {
      $scope.movies = data;
    });
  });
</script>
</head>
<body style="padding:12px;" ng-controller="MovieCtrl">
  <div ng-repeat="movie in movies">
    <h1>{{movie.title}} {{movie.id}}</h1>
    <p>{{movie.overview}}</p>
    <img ng-src="http://image.tmdb.org/t/p/w500{{movie.poster_path}}" style='width:200px'/>
  </div>
</body>
</html>

尝试使用 Angular.js获取 JSON。信息很好,但我相信状态也遇到了。导致屏幕上放置了 5 张图像,其中 4 张损坏,1 张图像以及数据良好。如何避免发送这些额外数据?

使用 AJAX 请求 JSON 数据

您希望通过 AJAX 请求获取 JSON 数据并呈现它。使用 $http 服务实现控制器,以提取数据并将其存储在作用域中。

<body ng-app="MyApp">
  <div ng-controller="PostsCtrl">
    <ul ng-repeat="post in posts">
      <li>{{post.title}}</li>
    </ul>
  </div>
</body>
var app = angular.module("MyApp", []);
app.controller("PostsCtrl", function($scope, $http) {
  $http.get('data/posts.json').
    success(function(data, status, headers, config) {
      $scope.posts = data;
    }).
    error(function(data, status, headers, config) {
      // log error
    });
});

http://fdietz.github.io/recipes-with-angular-js/consuming-external-services/requesting-json-data-with-ajax.html