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

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 프로퍼티에 응답을 설정합니다. 학생 모델을 사용하여 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파일을 웹 서버에 배포합니다. 파일을 열려면 네트워크 브라우저에서 서버 URL을 사용하여 파일을 열어 주세요testAngularJS.htm그런 다음 결과를 확인하세요。