【问题标题】:Why am I getting {"readyState":1} on the DOM rather than JSON data in AngularJS?为什么我在 DOM 上得到 {"readyState":1} 而不是 AngularJS 中的 JSON 数据?
【发布时间】:2018-06-20 20:10:07
【问题描述】:

我试图让 JSON 数据显示在 DOM 上(它只有 49 个项目),但我得到的是 {"readyState":1}。我这样做主要是为了测试我的代码是否正常工作。

我知道代码中的问题出在哪里,只是不知道语法应该是什么。

所以我的问题是我如何定义 $scope.dogs 以使 JSON 数据显示在页面上?我在 'mainCtrl' 控制器的 HTML 中有 {{dogs}}

这是 JS 文件:

const app = angular.module('dogBreedApp', []);

  app.controller('mainCtrl', function($scope) {
    $scope.dogs = $.ajax(settings).done(function (response) {
    });
  });

  var settings = {
    "async": true,
    "crossDomain": true,
    "url": "https://dogdatabase-d31f.restdb.io/rest/dogs",
    "method": "GET",
    "headers": {
      "content-type": "application/json",
      "x-apikey": "xxxxxxxxxxxxxxxxxxxxxx",
      "cache-control": "no-cache"
    }
  }
$.ajax(settings).done(function (response) {
  console.log(response);
});

设置变量和 ajax 东西是从我从中提取 JSON 的 restdb.io 服务复制和粘贴的,它记录 JSON 就好了。

我是开发的初学者,所以我相信这可能很简单。

谢谢!

【问题讨论】:

  • 在此调用$scope.dogs = $.ajax(settings).done(function (response) { }); 中,您要显示的内容将来自ajax 响应的response,不是吗?我想是“狗”。对吗?
  • 如果有,response的结构是什么?
  • 是的,没错。 response 作为狗信息的对象登录到控制台,这就是我希望到达 dom。
  • @Taylorg 你可能不应该发布你的 API 密钥(除非它不是问题)。
  • @Lex 嘿,好电话。这不是一个真正的问题,但你是对的,我会解决这个问题

标签: javascript angularjs json


【解决方案1】:

如果您打算使用 AngularJS,我建议使用 Angular 的 AJAX 方法而不是 jQuery 的方法。这是您可以做到的一种方法。如果您将$http 调用放在服务中,那么您可以返回承诺并在控制器中处理承诺解决方案。当像我在这里所做的那样使用 controllerAs 语法时,您需要将 this 放在局部变量中,因为在承诺解析中 this 将引用承诺而不是控制器,如果这有意义的话。对于 HTML 中的输出,我使用了 json 过滤器,以便显示缩进和换行符,而不仅仅是一个长字符串。

angular.module('app', [])
  .service('dogsService', function($http) {
    var service = {};
    service.getDogs = function() {
      return $http.get('https://dogdatabase-d31f.restdb.io/rest/dogs', {headers: {
        'x-apikey': 'xxxxxxxxxxxxxxxxxxxxxx'
        }
      }).then(response => response.data);
    };
    return service;
  })
  .controller('ctrl', function(dogsService) {
    var _this = this;
    this.dogs = [];
    dogsService.getDogs().then((data) => {
      _this.dogs = data;
    }).catch((error) => {
      console.error(error);
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl as $ctrl">
  <pre>{{$ctrl.dogs | json}}</pre>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    相关资源
    最近更新 更多