簡體   English   中英

使用AJAX請求JSON數據。 我沒看到結果

[英]Requesting JSON data with AJAX. I don't see result

我正在學習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}}

嘗試這個:

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

如果在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM