AngularJS AJAX - $http


$http 는 원격 서버에서 데이터를 읽기 위한 AngularJS 서비스입니다.


AngularJS $http

AngularJS $http서비스는 서버에 요청하고 응답을 반환합니다.

예시

서버에 간단한 요청을 하고 결과를 헤더에 표시합니다.

<div ng-app="myApp" ng-controller="myCtrl">

<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("welcome.htm")
  .then(function(response) {
    $scope.myWelcome = response.data;
  });
});
</script>

행동 양식

위의 예 .get는 서비스의 방법을 사용합니다 $http .

.get 메소드는 $http 서비스의 바로가기 메소드입니다. 몇 가지 바로 가기 방법이 있습니다.

  • .delete()
  • .get()
  • .head()
  • .jsonp()
  • .patch()
  • .post()
  • .put()

위의 방법은 모두 $http 서비스를 호출하는 바로 가기입니다.

예시

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http({
    method : "GET",
      url : "welcome.htm"
  }).then(function mySuccess(response) {
    $scope.myWelcome = response.data;
  }, function myError(response) {
    $scope.myWelcome = response.statusText;
  });
});

위의 예는 객체를 인수로 사용하여 $http 서비스를 실행합니다. 객체는 HTTP 메소드, url, 성공 시 수행할 작업 및 실패 시 수행할 작업을 지정합니다.



속성

서버의 응답은 다음 속성을 가진 개체입니다.

  • .config 요청을 생성하는 데 사용되는 개체입니다.
  • .data 서버로부터의 응답을 전달하는 문자열 또는 객체.
  • .headers 헤더 정보를 얻는 데 사용하는 함수입니다.
  • .status HTTP 상태를 정의하는 숫자.
  • .statusText HTTP 상태를 정의하는 문자열.

예시

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("welcome.htm")
  .then(function(response) {
    $scope.content = response.data;
    $scope.statuscode = response.status;
    $scope.statustext = response.statusText;
  });
});

오류를 처리하려면 .then메서드에 함수를 하나 더 추가합니다.

예시

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("wrongfilename.htm")
  .then(function(response) {
    // First function handles success
    $scope.content = response.data;
  }, function(response) {
    // Second function handles error
    $scope.content = "Something went wrong";
  });
});

JSON

응답에서 얻은 데이터는 JSON 형식이어야 합니다.

JSON은 데이터를 전송하는 훌륭한 방법이며 AngularJS 또는 기타 JavaScript 내에서 사용하기 쉽습니다.

예: 서버에는 15명의 고객이 포함된 JSON 개체를 반환하는 파일이 있으며 모두 records.

여기를 클릭하여 JSON 객체를 살펴보십시오.

×

고객.php

"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body><p>{\n\"records\":[\n{\"Name\":\"Alfreds Futterkiste\",\"City\":\"Berlin\",\"Country\":\"Germany\"},\n{\"Name\":\"Ana Trujillo Emparedados y helados\",\"City\":\"México D.F.\",\"Country\":\"Mexico\"},\n{\"Name\":\"Antonio Moreno Taquería\",\"City\":\"México D.F.\",\"Country\":\"Mexico\"},\n{\"Name\":\"Around the Horn\",\"City\":\"London\",\"Country\":\"UK\"},\n{\"Name\":\"B's Beverages\",\"City\":\"London\",\"Country\":\"UK\"},\n{\"Name\":\"Berglunds snabbköp\",\"City\":\"Luleå\",\"Country\":\"Sweden\"},\n{\"Name\":\"Blauer See Delikatessen\",\"City\":\"Mannheim\",\"Country\":\"Germany\"},\n{\"Name\":\"Blondel père et fils\",\"City\":\"Strasbourg\",\"Country\":\"France\"},\n{\"Name\":\"Bólido Comidas preparadas\",\"City\":\"Madrid\",\"Country\":\"Spain\"},\n{\"Name\":\"Bon app'\",\"City\":\"Marseille\",\"Country\":\"France\"},\n{\"Name\":\"Bottom-Dollar Marketse\",\"City\":\"Tsawassen\",\"Country\":\"Canada\"},\n{\"Name\":\"Cactus Comidas para llevar\",\"City\":\"Buenos Aires\",\"Country\":\"Argentina\"},\n{\"Name\":\"Centro comercial Moctezuma\",\"City\":\"México D.F.\",\"Country\":\"Mexico\"},\n{\"Name\":\"Chop-suey Chinese\",\"City\":\"Bern\",\"Country\":\"Switzerland\"},\n{\"Name\":\"Comércio Mineiro\",\"City\":\"São Paulo\",\"Country\":\"Brazil\"}\n]\n} </p></body></html>\n<script>\n    function gtElInit() {\n        var lib = new google.translate.TranslateService();\n        lib.translatePage('', 'ko', function() {});\n    }\n</script>\n<script src=\"https://translate.google.com/translate_a/element.js?cb=gtElInit&amp;client=wt&amp;hl=ko&amp;te=pod\" type=\"text/javascript\"></script>\n\n\n</html>"

예시

ng-repeat지시문은 배열을 반복하는 데 적합합니다 .

<div ng-app="myApp" ng-controller="customersCtrl">

<ul>
  <li ng-repeat="x in myData">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
  $http.get("customers.php").then(function(response) {
    $scope.myData = response.data.records;
  });
});
</script>

응용 프로그램 설명:

응용 프로그램은 개체 를 사용하여 customersCtrl컨트롤러를 정의합니다.$scope$http

$http외부 데이터를 요청하기 위한 XMLHttpRequest 객체 입니다.

$http.get()https://www.w3schools.com/angular/customers.php 에서 JSON 데이터읽습니다 .

myData성공하면 컨트롤러 는 서버의 JSON 데이터를 사용하여 범위에 속성 을 만듭니다 .