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

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

问题描述

我是新使用AngularJS,我有一个问题解析JSON响应。这是HTML code我使用的:

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>

这是使用AngularJS JavaScript的code:

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();
}

中的HTML是显示变量$ scope.response与JSON服务器返回,但它没有显示在列表顶部什么。该JSON是完全格式化,但是$ scope.cars变量似乎总是空的。

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.

我在做什么错了?

非常感谢,

GA

推荐答案

$ http.get将解析JSON为您服务。你并不需要自己解析它。

$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天全站免登陆