English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

AngularJS Ajax

AngularJS fournit le contrôle $http, qui peut être utilisé comme service pour lire des données à partir du serveur. Le serveur effectue des appels à la base de données pour obtenir les enregistrements nécessaires. AngularJS nécessite des données au format JSON. Une fois les données préparées, vous pouvez obtenir des données du serveur en utilisant $http de la manière suivante-

function studentController($scope,$https:) {
   var url = "data.txt";
   $https:.get(url).success(function(response) {
      $scope.students = response; 
   });
}

Ici, le fichier data.txt contient des enregistrements d'étudiants. Le service $http effectue une appel AJAX et configure la réponse sur son attribut students. Le modèle d'étudiant peut être utilisé pour dessiner un tableau HTML.

实例

data.txt

[
   {
      "Name" : "Sea Gull",
      "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-Ajax示例</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 = "/run/angularjs/data.txt";
            $http.get(url).then( function(response) {
               $scope.students = response.data;
            });
         }
      </script>
      
      <script src = "https://cdn.staticfile.org/angular.js/1.2.15/angular.min.js">
      </script>
      
   </body>
</html>
测试看看‹/›

输出结果

要执行此示例,您需要将testAngularJS.htmdata.txt文件部署到Web服务器。在网络浏览器中使用服务器的URL打开文件testAngularJS.htm,然后查看结果。