AngularJS AJAX - $http

$http는 AngularJS의 서비스로, 원격 서버에서 데이터를 읽기 위해 사용됩니다。

AngularJS $http

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

实例

서버에 간단한 요청을 보내고 타이틀에 결과를 표시합니다:

<div ng-app="myApp" ng-controller="myCtrl">
<p>오늘의 환영 메시지는:</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>

직접 시도해 보세요

메서드를 사용했습니다

위의 예제는 $http 서비스의 .get 메서드。

.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 对象。

实例

The ng-repeat directive is perfect for looping through an array:

<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 컨트롤러가 scopehttp 객체입니다.

$httpXMLHttpRequest 객체외부 데이터를 요청하는 데 사용됩니다.

$http.get() https://www.codew3c.com/angular/customers.php에서 가져옴 JSON 데이터

성공하면, 컨트롤러가 스코프에서 하나의 속성을 생성합니다 myData서버에서 온 JSON 데이터가 포함되어 있습니다.