【问题标题】:unable to Retrieve data from JSON file using Angular js无法使用 Angular js 从 JSON 文件中检索数据
【发布时间】:2025-12-21 00:45:06
【问题描述】:

enter image description here我无法使用 Angular Js 从 Json 文件中检索数据。 我正在尝试使用 Angular Js 中的单击功能从 URL 获取 Json 数据,并且在单击按钮时在表中添加空 tr td。

 <!doctype html>
    <html lang="en" ng-app="sampleapp">
      <head>
       {% load staticfiles %}   
        <meta charset="utf-8">
        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="{% static 'bootstrap/js/angular.min.js'%}"></script>
        <script  type="text/javascript" src="{% static 'bootstrap/js/jquery.min.js'%}"></script>
        <script src="{% static 'bootstrap/js/bootstrap.min.js'%}" type="text/javascript"></script>
        <script type="text/javascript" src="{% static '/bootstrap/js/app_ang.js'%}"></script>
      </head>
      <body >

            <div class="col-sm-12" ng-controller="tablejsonCtrl">
                 <button class="clickbutton" ng-click="jsonclick();">Show-json</button>
                 <table rule="all" class="table table-bordered table-hover ">
                    <tr>
                        <th>Name</th>
                        <th>Price</th>
                        <th>Description</th>
                        <th>Calories</th>
                        <th>isbest</th>
                    </tr>
                    <tr ng-repeat="value in students.breakfast_menu.food">
                        <td>{{value.name}}</td>
                        <td>{{value.price}}</td>
                        <td>{{value.description}}</td>
                        <td>{{value.calories}}</td>
                        <td>{{value.isbest}}</td>
                    </tr>
                 </table>

            </div>
      </body>
    </html>
var app =angular.module('sampleapp', [])    
app.controller("tablejsonCtrl", function ($scope, $http) {        
    $scope.jsonclick = function () {
        var url = "http://127.0.0.1:8000/static/waste/test.json";
        $http.get(url).then(function(response) {
            $scope.students = response.data;
        });

      }
});

【问题讨论】:

    标签: html angularjs django


    【解决方案1】:

    您可以在本地使用 HTTP 请求。 仅适用于 1.6 以上的 Angular 版本

    $http.get('./path-to-JSON-file/../someFile.json').
      then(function onSuccess(response) {
         angular.extend(_this, data);
         defer.resolve();
      }).
      catch(function onError(response) {
       console.log(response);
      });
    

    进一步研究:CLICK HERE

    【讨论】:

      【解决方案2】:

      而不是使用“.then”尝试使用.success方法,所以替换这个:

         $http.get(url).then(function(response) {
              $scope.students = response.data;
          });
      

      有了这个:

      $http.get('url').success(function (response){
          $scope.students= response;
      });
      

      【讨论】: