使用 AngularJS 解析 JSON 响应的问题 [英] Problems parsing a JSON response using AngularJS

查看:32
本文介绍了使用 AngularJS 解析 JSON 响应的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 AngularJS 的新手,在解析 json 响应时遇到问题.这是我使用的 HTML 代码:

<头><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><身体><div ng-controller="CarCtrl"><ul><li ng-repeat="汽车中的汽车">{{车名}}<p>{{car.speed}}</p><小时><p>{{响应}}</p>

</html>

这是使用 AngularJS 的 Javascript 代码:

function CarCtrl($scope, $http) {$scope.getAllCars = 函数 () {$scope.url = 'getAllCars';$http.get($scope.url).success(function (data, status) {$scope.response = 数据;var carFromServer = JSON.parse(data);$scope.cars = carsFromServer.allCars;}).错误(函数(数据,状态){$scope.response = '请求失败';});}$scope.getAllCars();}

HTML 显示变量 $scope.response 和服务器返回的 JSON,但它没有在顶部的列表中显示任何内容.JSON 格式完美,但 $scope.cars 变量似乎始终为空.

我做错了什么?

非常感谢,

GA

解决方案

$http.get 将为您解析 json.您不需要自己解析它.

 $scope.cars = data.allCars;

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

解决方案

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

   $scope.cars = data.allCars;

这篇关于使用 AngularJS 解析 JSON 响应的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆