AngularJS:如何将 JSON 数据加载到作用域变量中

问题描述 投票:0回答:5

我正在创建一个个人网站,我可以在其中不断更新内容,而无需操作

HTML
。我试图通过简单地加载和更新
JSON
文件来实现此目的。但现在,我无法将
JSON
数据加载到
scope
变量中。

HTML

<!doctype html>

<html>
    <head>
        <script src="angular.min.js" type="text/javascript"></script>
        <script src="maincontroller.js" type="text/javascript"></script>
    </head>
    <body>
        <div ng-app="mainApp" ng-controller="mainController">
            <div id="content">
                <div ng-repeat="content in contents">
                    <h2>{{content.heading}}</h2>
                    <p>{{content.description}}</h2>
                </div>
            </div>
        </div>
    </body>
</html>

主控制器.js

var myapp = angular.module('mainApp', []);
myapp.controller('mainController',function($scope,$http){

    $scope.contents = null;
    $http.get('mainContent.json')
        .success(function(data) {
            $scope.contents=data;
        })
        .error(function(data,status,error,config){
            $scope.contents = [{heading:"Error",description:"Could not load json   data"}];
        });

    //$scope.contents = [{heading:"Content heading", description:"The actual content"}];
    //Just a placeholder. All web content will be in this format
});

这就是

JSON
文件的样子

[
    {"heading":"MyHeading","description":"myDescription"},
]

我实际上尝试按照here给出的解决方案进行操作,但它没有加载存储在同一文件夹中的

JSON
文件。我得到的输出来自错误处理函数,如上所述,该函数表示
Error: Cannot load JSON data

我做错了什么?

编辑:我将相同的代码放在 plunker 上,效果很好。它只是无法在我的本地计算机上运行。

javascript json angularjs
5个回答
6
投票

修改了您的方法使用此方法并检查输出。

var myapp=angular.module('mainApp',[]);
myapp.controller('mainController',function($scope,$http){
    $scope.content = null;
    $http.get('urlpath'}).
        success(function(data, status, headers, config) {
            $scope.contents=data;
        }).error(function(data, status, headers, config) {          
    });
});

或者我看到的另一个好的做法

使用工厂服务方法:-

angular.module('mainApp').factory('Myservice', function($http){
    return {
        getdata: function(){
              return $http.get('url'); // You Have to give Correct Url either Local path or api etc 
           
        }
    };
});

将上述服务注入到Controller中

控制器:-

angular.module('mainApp',[]).controller('mainController',function($scope,Myservice){
        $scope.content = null;
         Myservice.getdata().success(function (data){
           alert('Success');
           $scope.content=data[0]; // as per  emilySmitley Answer which is Working Good
         });
      });

如果您有任何问题,请告诉我。祝你好运


5
投票

您的 json 文件有一个数组,数组中的第一个也是唯一一个元素是 json 对象。当

.success()
触发时,数据被传递到 lambda 函数中,数据是一个数组,而不仅仅是 json。您所要做的就是访问数组的第零个元素。

所以这个:

.success(function(data) {
    $scope.contents = data;
})

应该是这样的:

.success(function(data) {
    $scope.contents = data[0];
})

此外,您应该检查

data[0]
以确保它是 json,如果它未验证,您可能应该对其调用
parseJSON(data[0])


2
投票
var myapp=angular.module('mainApp',[]);
myapp.controller('mainController',function($scope,$http){
    $scope.content = null;
    $http({method: 'GET', url: 'mainContent.json'}).
        success(function(data, status, headers, config) {
            $scope.contents=data;
        }).error(function(data, status, headers, config) {          
    });
});

在 Web Server 中发布并添加了 .json 的 Mime 类型。成功了。


0
投票

按如下方式更改 mainController.js 和 JSON 文件。这里我使用 wamp 服务器作为我的本地服务器。

var myapp = angular.module('mainApp', []);
myapp.controller('mainController', function($scope, $http) {
  $http.get('http://localhost/stackoverflow/angular/test1/database.json').success (function(data) {
    $scope.contents = data.records;
  })
});

JSON 文件:

{
 "records":
 [
    {"heading":"MyHeading","description":"myDescription"}
 ]
}

0
投票

不知道你是否还能找到解决方案。 如果没有,请尝试这个。 使用 localhost 服务器时,服务器无法找到 json 文件。 要解决这个问题,只需将文件重命名为 mainContent.txt 即可,除此之外,您的代码是完美的。 但请记住,这仅适用于开发阶段,一旦您计划实时部署站点,请改回 .json 文件。

更新了 $http 请求:-

$scope.contents = null;
$http.get('mainContent.json')
    .success(function(data) {
        $scope.contents=data;
    })
    .error(function(data,status,error,config){
        $scope.contents = [{heading:"Error",description:"Could not load json   data"}];
    });
© www.soinside.com 2019 - 2024. All rights reserved.