Problems parsing a JSON response using AngularJS

心已入冬 提交于 2020-01-28 09:51:31

问题


I am new using AngularJS and I am having an issue parsing a json response. This is the HTML code I am using:

<!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:

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.

What am I doing wrong?

Many thanks,

GA


回答1:


$http.get will parse the json for you. You do not need to parse it yourself.

   $scope.cars = data.allCars;



回答2:


Just parse your data like that

function (response,httpStatus) {    
                 alert('response' + angular.toJson(response));                  
         }

It is built-in feature of angularjs.



来源:https://stackoverflow.com/questions/17917238/problems-parsing-a-json-response-using-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!