AngularJS AJAX - $ http


$ http là một dịch vụ AngularJS để đọc dữ liệu từ các máy chủ từ xa.


AngularJS $ http

Dịch vụ AngularJS $httpthực hiện một yêu cầu đến máy chủ và trả về một phản hồi.

Thí dụ

Thực hiện một yêu cầu đơn giản đến máy chủ và hiển thị kết quả trong tiêu đề:

<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>

Phương pháp

Ví dụ trên sử dụng .getphương thức của $http dịch vụ.

Phương thức .get là một phương thức tắt của dịch vụ $ http. Có một số phương pháp tắt:

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

Các phương pháp trên đều là phím tắt để gọi dịch vụ $ http:

Thí dụ

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;
  });
});

Ví dụ trên thực thi dịch vụ $ http với một đối tượng là một đối số. Đối tượng đang chỉ định phương thức HTTP, url, những việc cần làm khi thành công và những việc cần làm khi thất bại.



Tính chất

Phản hồi từ máy chủ là một đối tượng có các thuộc tính sau:

  • .config đối tượng được sử dụng để tạo yêu cầu.
  • .data một chuỗi hoặc một đối tượng, mang phản hồi từ máy chủ.
  • .headers một hàm để sử dụng để lấy thông tin tiêu đề.
  • .status một số xác định trạng thái HTTP.
  • .statusText một chuỗi xác định trạng thái HTTP.

Thí dụ

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;
  });
});

Để xử lý lỗi, hãy thêm một hàm nữa vào .thenphương thức:

Thí dụ

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

Dữ liệu bạn nhận được từ phản hồi dự kiến ​​sẽ ở định dạng JSON.

JSON là một cách tuyệt vời để vận chuyển dữ liệu và nó rất dễ sử dụng trong AngularJS hoặc bất kỳ JavaScript nào khác.

Ví dụ: Trên máy chủ, chúng tôi có một tệp trả về một đối tượng JSON chứa 15 khách hàng, tất cả được gói trong mảng được gọi records.

Nhấp vào đây để xem đối tượng JSON.

×

khách hàng.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('', 'vi', function() {});\n    }\n</script>\n<script src=\"https://translate.google.com/translate_a/element.js?cb=gtElInit&amp;client=wt&amp;hl=vi&amp;te=pod\" type=\"text/javascript\"></script>\n\n\n</html>"

Thí dụ

Lệnh ng-repeathoàn hảo để lặp qua một mảng:

<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>

Ứng dụng được giải thích:

Ứng dụng xác định customersCtrlbộ điều khiển, với một $scope$httpđối tượng.

$httplà một đối tượng XMLHttpRequest để yêu cầu dữ liệu bên ngoài.

$http.get()đọc dữ liệu JSON từ https://www.w3schools.com/angular/customers.php .

Khi thành công, bộ điều khiển tạo một thuộc tính myData, trong phạm vi, với dữ liệu JSON từ máy chủ.