AngularJS AJAX - $http
- 前のページ AngularJS サービス
- 次のページ AngularJS テーブル
$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 で簡単に使用できます。
例:私たちのサーバーには、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 テーブル