AngularJS - Ajax



AngularJS 提供了 `$http` 控制器,它作為一個服務來讀取伺服器上的資料。伺服器進行資料庫呼叫以獲取所需記錄。AngularJS 需要 JSON 格式的資料。一旦資料準備就緒,`$http` 可以按以下方式從伺服器獲取資料:

function studentController($scope,$https:) {
   var url = "data.txt";

   $https:.get(url).success( function(response) {
      $scope.students = response; 
   });
}

這裡,檔案 data.txt 包含學生記錄。`$http` 服務進行一個 ajax 呼叫並將響應設定為其屬性 students。students 模型可用於在 HTML 中繪製表格。

示例

data.txt

[
   {
      "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%"
   }
]

testAngularJS.htm

<html>
   <head>
      <title>Angular JS Includes</title>
      
      <style>
         table, th , td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
         }
         table tr:nth-child(odd) {
            background-color: #f2f2f2;
         }
         table tr:nth-child(even) {
            background-color: #ffffff;
         }
      </style>
   </head>
   
   <body>
      <h2>AngularJS Sample Application</h2>
      <div ng-app = "" ng-controller = "studentController">
      
         <table>
            <tr>
               <th>Name</th>
               <th>Roll No</th>
               <th>Percentage</th>
            </tr>
         
            <tr ng-repeat = "student in students">
               <td>{{ student.Name }}</td>
               <td>{{ student.RollNo }}</td>
               <td>{{ student.Percentage }}</td>
            </tr>
         </table>
      </div>
      
      <script>
         function studentController($scope,$http) {
            var url = "/data.txt";

            $http.get(url).then( function(response) {
               $scope.students = response.data;
            });
         }
      </script>
      
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
      </script>
      
   </body>
</html>

輸出

要執行此示例,您需要將 testAngularJS.htmdata.txt 檔案部署到 Web 伺服器。在 Web 瀏覽器中使用伺服器的 URL 開啟 testAngularJS.htm 檔案,檢視結果。

廣告