在JavaScript angular js中从URL获取数据(Ajax)

时间:2016-02-05 09:45:10

标签: javascript angularjs json ajax

我正在使用角移动Ui框架工作。我从控制器中的URL获取数据。但是现在我想获得成功的特定数据部分。我将展示我的代码片段以供提示。

HTML:

new Date(timestamp).toString()

HTML OUTPUT
enter image description here

控制器:

   <div class="jumbtron scrollable-content text-center bg-color">
   <div class="row">
          <div class="bgImage">  
          </div>
          <div class="btn-group img-responsive"  ng-controller="MyControllerCity"> 
              <div ng-repeat="prdct in cityProduct">
                   <a href="#/category-prduct" style="color:#763428; font-weight:bold;">
                      <img  src="{{prdct.categoryImage}}">
                    </a>
              </div>
          </div>

    </div>
</div>
  

console.log(“aaaaaaa”+ cityProduct.categoryId);

但是categoryId没有显示在控制台中。

JSON截屏: enter image description here

以下是JSON响应:

.controller('MyControllerCity',function($scope, $http){ 
        $http({
                method:'get',
                url:'http://192.168.0.3/sf/app/city-home/1',
                headers: {'Content-Type': 'application/json'},
            }).success(function(data, status,headers, config) {
                $scope.cityProduct = data; 
                console.log("aaaaaaa" + cityProduct.categoryId);

            }).error(function(data, status, headers ,config) {

        })

})

我想在控制台中获取categoryId。

我用过:

  

console.log(“categoryId”+ cityProduct [0] .categoryId);

但是出现了一些错误,我将向您显示控制台错误的屏幕截图: enter image description here

提前感谢。

2 个答案:

答案 0 :(得分:3)

您的JSON是一个对象数组,因此您需要像这样访问它:

$scope.cityProduct[0].categoryId

或更具活力的东西:

$scope.cityProduct.forEach(function(product) {
    console.log(product.categoryId);
});

另请注意,您是第一次设置cityProduct变量后错过了$ scope。

答案 1 :(得分:2)

以下一行让您感到困惑:

$scope.cityProduct = data;

连续收到的数据是一组对象作为JSON响应。使用索引$scope.cityProduct[0]访问数组元素。

console.log("aaaaaaa" + cityProduct.categoryId);

在该行中,您应该在$scope.之前写cityProduct.categoryId

这是固定代码:

.controller('MyControllerCity',function($scope, $http){ 
        $http({
                method:'get',
                url:'http://192.168.0.3/sf/app/city-home/1',
                headers: {'Content-Type': 'application/json'},
            }).success(function(data, status,headers, config) {
                $scope.cityProduct = data;
                // to access first element's categoryId 
                console.log("aaaaaaa" + $scope.cityProduct[0].categoryId);
                // iterate here to access all elements' categoryId
                $scope.cityProduct.forEach(function(product) {
                 console.log(product.categoryId);
                }); 
            }).error(function(data, status, headers ,config) {

        })

})