AngularJS 獲取JSON數據

一、使用$http

  • 我們可以使用內置的$http服務直接同外部進行通信。$http服務只是簡單的封裝了瀏覽器原生的XMLHttpRequest對象。
  • $http服務是只能接受一個參數的函數,這個參數是一個對象,包含了用來生成HTTP請求的配置內容這個函數返回一個promise對象,具有success和error兩個方法。
    這兩個方法最基本的使用場景如下:
$http({
    method: 'GET',
    url: '/api/users.json'
}).success(function(data,status,headers,config){
    //當相應準備就緒時調用
}).error(function(data,status,headers,config){
    //當響應以錯誤狀態返回時調用
});

二、AngularJS獲取JSON數據實例代碼

1、data.json:

[
  {
    "Name":"Mahesh Parashar",
    "RollNo":101,
    "Percentage":"80%"
  },

  {
    "Name":"Dinkar Kad",
    "RollNo":201,
    "Percentage":"70%"
  },

  {
    "Name":"Robert",
    "RollNo":191,
    "Percentage":"75%"
  },

  {
    "Name":"Julian Joe",
    "RollNo":111,
    "Percentage":"77%"
  }
]

2、index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>angular_learn</title>
    <script src="js/angular-1.3.0.js"></script>
</head>
<body>
    <div class="dataList" ng-app="myApp" ng-controller="myController">
        <ul>
            <!--在讀取數據的區域添加ng-repeat-->
            <li ng-repeat="student in students">
                <span>{{student.Name}}</span>
                <span>{{student.RollNo}}</span>
                <span>{{student.Percentage}}</span>
            </li>
        </ul>
    </div>

    <script src="js/angular-1.3.0.js"></script>
    <script>
        var myApp = angular.module("myApp",[]);
        myApp.controller("myController",function ($scope, $http) {
           var dataUrl = "json/data.json";
           //獲取數據
           $http.get(dataUrl).success(function (data) {
               $scope.students = data;
           }).error(function () {
               alert("出錯");
           });
        });
    </script>
</body>
</html>

三、方法總結

1、 配置對應的控制器,將$scope、$http服務注入改控制器中;
2、使用$http.get(),把將要讀取的數據文件的url寫入;
3、使用回調函數,成功時,將所得的data賦給$scope作用域下的變量products。
4、由前臺使用ng-repeat指令進行遍歷逐一取出數據

部分內容轉載自:面具哥布林的博客

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章