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 และตั้งค่าการตอบสนองต่อนักเรียนของสถานที่ให้บริการ แบบจำลองนักเรียนสามารถใช้เพื่อวาดตารางใน 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.htmและdata.txtกับเว็บเซิร์ฟเวอร์ เปิดไฟล์testAngularJS.htmโดยใช้ URL ของเซิร์ฟเวอร์ของคุณในเว็บเบราว์เซอร์และดูผลลัพธ์