【问题标题】:Why can't I retrieve data from my Json file?为什么我无法从我的 Json 文件中检索数据?
【发布时间】:2016-04-29 21:56:48
【问题描述】:

我正在尝试从我的 json 文件中获取一个小型测试项目的数据。我在开发人员工具中没有收到任何错误,当我在请求后执行 console.log(data) 时,我从文件中获取数据。

这是我的角码:

var app = angular.module('myApp', []);

app.controller('MainController', ['$scope','$http', function($scope,     $http){
  $scope.todos = [];
  $http.get('db/todos.json')
    .then(function(data){
      $scope.todos = data;

    });
 }]);

这是我的 html 文件:

<!doctype html>
<html ng-app="myApp">
<head>
<base href="/">
<title>My todo</title>
<link rel="stylesheet"  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://code.angularjs.org/1.5.5/angular.js"></script>
  <script src="/js/app.js"></script>
</head>
<body>
  <div class="container" ng-controller="MainController">
     <div class="row">
     <h1>Your todos</h1>
     <li ng-repeat="todo in todos">
        {{ todo.name }}
      <li>
    </div>
  </div>
</body>
</html>

在我的站点中,ng-repeat 只打印出六个项目符号,这是错误的,因为我的 json 文件中只有两个条目。这也是我从我的 console.log(data) 得到的:

Object {data: Object, status: 200, config: Object, statusText: "OK"}
config: Object
data:Object
headers:(name)
status:200
statusText:"OK"
__proto__:Object

关于我可能错过的任何想法?

【问题讨论】:

    标签: javascript html angularjs json


    【解决方案1】:

    当使用.then 时,实际的响应数据在response.data 中,所以如果你像这样改变它,你的代码就可以工作:

    .then(function(response){
        $scope.todos = response.data;
    });
    

    【讨论】:

    • 嗯,我不知道,我大部分时间都在使用 .success。现在我将&lt;li&gt; 元素打印了两次,但没有数据。是否还有其他方法可以访问 index.html 文件中的数据?
    • @captain 不,还是一样,你能不能在.then 中做console.log(response.data) 并检查是否一切都好?
    • 这出现在控制台中:Object {todos: Array[2]} 带有一个下拉菜单,其中0: Object checked: "false" name: "Go shopping" 然后是几乎相同的下一个对象
    • $scope.todos = response.data 应该是 $scope.todos = response.data.todos; 然后
    • 这行得通,但现在我从&lt;li&gt; 元素中得到了第三个要点。我必须弄清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 2019-12-30
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    相关资源
    最近更新 更多