gpt4 book ai didi

javascript - 从 $http 调用解析 AngularJS 中的 JSon 数据

转载 作者:数据小太阳 更新时间:2023-10-29 05:19:03 24 4
gpt4 key购买 nike

我对网络开发和 AngularJS 都很陌生。我正在尝试编写一个网页,该网页将根据我服务器上的 JSON 文件自动更新其信息。我可以获得 json 数据,但我似乎无法解析传入的数据。我验证了 json 数据只是为了确保我正确地编写了它,但是无论何时我在网站上显示它都只是显示为单个字符串。我无法访问个别成员。我的工厂和 Controller 在下面。任何帮助将不胜感激!!

var MyController = function($scope, $log, MyFactory) {
$scope.notes =[];

function init() {
MyFactory.getNotes()
.success(function(notes){
$scope.notes = JSON.parse(notes);
})
.error(function(data, status, headers, config) {
$log.log(data.error + ' ' + status);
});
}

init();

angular.module('MyApp')
.controller('MyController', MyController);
};

还有工厂:

    var MyFactory = function($http) {
var factory = {};
factory.getNotes = function() {
return $http.get('/ci/data.json');
};
return factory;
};

angular.module('MyApp').factory('MyFactory',
MyFactory);

我承认代码和问题很粗糙,但我才刚刚开始。任何有关体系结构和样式的额外帮助也将不胜感激!提前致谢!

最佳答案

  1. 您不需要将响应解析为 json。如果源文件为您提供有效的 json,angular 就知道它的 json。

  2. 在您的 Controller 中,尝试console.log($scope.notes)。如果使用 google chrome,您会在控制台中漂亮地打印出 json 结果,您知道您的 factory 正在运行。

  3. 使用 Angular forEach 遍历结果以对其执行某些操作。

    angular.forEach($scope.notes, function(note) {
    console.log(note);
    });

关于javascript - 从 $http 调用解析 AngularJS 中的 JSon 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23179757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com