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) {
// 第一個函式處理成功
$scope.content = response.data;
}, function(response) {
// 第二個函式處理錯誤
$scope.content = "Something went wrong";
});
});
自己動手試一試 »
JSON
從響應中獲取的資料預計是 JSON 格式。
JSON 是一種很棒的資料傳輸方式,在 AngularJS 或任何其他 JavaScript 中都很容易使用。
示例:在伺服器上,我們有一個檔案,它返回一個 JSON 物件,包含 15 位客戶,所有客戶都包含在一個名為 records
的陣列中。
示例
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://w3schools.tw/angular/customers.php 讀取JSON 資料。
成功時,控制器會在作用域中建立一個名為 myData
的屬性,其中包含來自伺服器的 JSON 資料。