使用AJAX请求JSON数据。我看不到结果

时间:2014-01-18 12:46:48

标签: javascript json angularjs

我正在学习Angular JS。为什么我没有看到任何结果?

以下是我的例子:

HTML:

...
<div ng-controller="PostsCtrl">
    <ul ng-repeat="post in posts">
      <li>{{post.desc}}</li>
    </ul>
  </div>
...

JS:

var app = angular.module("MyApp", []);

app.controller("PostsCtrl", function($scope, $http) {
  $http.get('http://www.site.com/post?format=json').
    success(function(data, status, headers, config) {
      $scope.posts = data;
    }).
    error(function(data, status, headers, config) {
      // log error
    });
});
来自http://www.site.com/post?format=json

JSON

{"book": [{"added": "2013-10-09T15:16:45", "desc": "Expert Python Programming shows how Python development should be done with best practices and expert design tips.", "id": 2, "isbn": "ISBN-10: 1430258098", "link": "http://www.amazon.com/Pro-Django-Marty-Alchin/dp/1430258098/ref=sr_1_43?ie=UTF8&qid=1372941168&sr=8-43&keywords=django", "price": "32", "read_pages": 124, "resource_uri": "/api/book/2/", "title": "Pro Django", "total_pages": 376, "user": "/api/user/1/"}, {"added": "2014-01-17T15:25:34", "desc": "asdg", "id": 3, "isbn": "555", "link": "http://www.fb.pl/", "price": "5", "read_pages": 5, "resource_uri": "/api/book/3/", "title": "asdg", "total_pages": 5, "user": "/api/user/1/"}], "meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 2}}

2 个答案:

答案 0 :(得分:0)

试试这个:

success(function(data, status, headers, config) {
    $scope.posts = data.book;
})

答案 1 :(得分:0)

当范围内的数据在ng-click等常规AngularJS事件之外更改时,您需要手动调用$scope.$apply() 在范围内应用任何更改。

另外,正如karaxuna建议您应该从json结果中读取book属性

这应该有效:

var app = angular.module("MyApp", []);

app.controller("PostsCtrl", function($scope, $http) {
  $http.get('http://www.site.com/post?format=json')
    .success(function(data, status, headers, config) {
        // Manually apply changes here
        $scope.$apply(function() {
            $scope.posts = data.book;
        });
    }).
    error(function(data, status, headers, config) {
      // log error
    });
});

请参阅此博文章,其中详细介绍了它:http://jimhoskins.com/2012/12/17/angularjs-and-apply.html