AngularJS AJAX - $http
- 上一頁 AngularJS 服務
- 下一頁 AngularJS 表格
$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>
方法
上面的例子使用 $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
控制器,具有 scope
和 http
對象。
$http
是一個 XMLHttpRequest 對象,用于請求外部數據。
$http.get()
從 https://www.codew3c.com/angular/customers.php 讀取 JSON 數據。
成功后,控制器在作用域中創建一個屬性 myData
,其中包含來自服務器的 JSON 數據。
- 上一頁 AngularJS 服務
- 下一頁 AngularJS 表格