【问题标题】:Not getting json data from json-angularjs call to an external url with $http.get未使用 $http.get 从 json-angularjs 调用外部 url 获取 json 数据
【发布时间】:2017-07-25 09:08:35
【问题描述】:

控制器代码:

var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope, $http) {
    $http.get('data.json').then(function(data) {
        $scope.artist = data;
    });
});

html代码:

<div class="main" ng-controller="myController">

    <ul class="artistlist">

        <li class="artist cf" ng-repeat="x in artist">

            <img ng-src="images/{{x.shortname}}_tn.jpg" alt="Photo of {{x.name}}">

            <div class="info">

                <h2>{{x.name}}</h2>

                <h3>{{x.reknown}}</h3>

            </div>

        </li>

    </ul>

</div>

【问题讨论】:

  • 控制台有错误吗?你是什​​么console.log(数据)?您是在为您的应用程序提供服务还是尝试直接从文件系统访问data.json
  • console.log(data) 工作正常并显示数据:Object {data: Array(9), status: 200, config: Object, statusText: "OK", headers: function}
  • 从您的错误看来,您在应用程序的某些部分使用 MyController 作为控制器的名称,在上面的 sn-p 中使用 myController
  • 抱歉上面的错误我没有保存 HTML 文件现在它显示数据:对象 {data: Array(9), status: 200, config: Object, statusText: "OK",标题:函数}

标签: javascript html angularjs json controller


【解决方案1】:

试试这个:你的控制器

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

myApp.controller("myController", ["$scope", "$http", function ($scope, $http) {
    $http.get("data.json").then(
        function (response) { $scope.artist = response.data },
        function (error) { console.log(error) }
    )
}])

确保检查浏览器的控制台

【讨论】:

    【解决方案2】:

    $http 服务具有用于获取详细信息的数据属性。

    数据 - {string|Object} - 使用转换函数转换的响应体

    像这样更改你的控制器代码

    var myApp=angular.module('myApp',[]);
    
    myApp.controller('myController', function($scope,$http){
    
        $http.get('data.json').then( function(response){
        $scope.artist = response.data;
        });
    });
    

    然后用ng-app="myApp"初始化你的html

    【讨论】:

    • 你怎么可能知道接收到的json的结构呢?你怎么知道它嵌套在data.data下面?
    • 仍然没有来自 json 文件的数据
    • 你的数据包含什么?@KaranTiwari
    • @JeremyThille 我认为如果您使用的是 .then,角度将在响应的数据键中发送响应
    • 哦,我明白了,不错。 @Vivz你应该在你的回答中这么说:)
    猜你喜欢
    • 2017-12-31
    • 2016-03-30
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2016-05-25
    • 2013-05-06
    相关资源
    最近更新 更多