使用 AngularJS 解析 JSON 响应的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17917238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Problems parsing a JSON response using AngularJS
提问by G A
I am new using AngularJS and I am having an issue parsing a json response. This is the HTML code I am using:
我是使用 AngularJS 的新手,在解析 json 响应时遇到问题。这是我正在使用的 HTML 代码:
<!DOCTYPE html>
<html ng-app>
<head>
<script src="@routes.Assets.at("javascripts/angular.min.js")" type="text/javascript"</script>
<script src="@routes.Assets.at("javascripts/carLibrary.js")" type="text/javascript"></script>
</head>
<body>
<div ng-controller="CarCtrl">
<ul>
<li ng-repeat="car in cars">
{{car.name}}
<p>{{car.speed}}</p>
</li>
</ul>
<hr>
<p>{{response}}</p>
</div>
</body>
</html>
And this is the Javascript code using AngularJS:
这是使用 AngularJS 的 Javascript 代码:
function CarCtrl($scope, $http) {
$scope.getAllCars = function () {
$scope.url = 'getAllCars';
$http.get($scope.url).success(function (data, status) {
$scope.response = data;
var carsFromServer = JSON.parse(data);
$scope.cars = carsFromServer.allCars;
}).error(function (data, status) {
$scope.response = 'Request failed';
});
}
$scope.getAllCars();
}
The HTML is showing the variable $scope.response with the JSON returned by the server, but it is not showing anything in the list at the top. The JSON is perfectly formatted, however $scope.cars variable seems to be always empty.
HTML 显示变量 $scope.response 和服务器返回的 JSON,但它没有在顶部的列表中显示任何内容。JSON 格式完美,但 $scope.cars 变量似乎始终为空。
What am I doing wrong?
我究竟做错了什么?
Many thanks,
非常感谢,
GA
遗传算法
回答by Karen Zilles
$http.get will parse the json for you. You do not need to parse it yourself.
$http.get 将为您解析 json。您不需要自己解析它。
$scope.cars = data.allCars;
回答by shiv.mymail
Just parse your data like that
就这样解析你的数据
function (response,httpStatus) {
alert('response' + angular.toJson(response));
}
It is built-in feature of angularjs.
它是angularjs.

