AngularJS XMLHttpRequest


$httpAngularJS の中心的なサービスの一つで、リモートサーバーからデータを読み取るために使用されます。

使用形式:

// 简单的 GET 请求,可以改为 POST
$http({
    method: 'GET',
    url: '/someUrl'
}).then(function successCallback(response) {
        // 请求成功执行代码
    }, function errorCallback(response) {
        // 请求失败执行代码
});

省略記法

POST と GET の省略記法の形式:

$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);

さらに、以下の省略記法もあります:

  • $http.get
  • $http.head
  • $http.post
  • $http.put
  • $http.delete
  • $http.jsonp
  • $http.patch

詳細については、以下を参照してください:https://docs.angularjs.org/api/ng/service/$http


JSONファイルの読み取り

以下はWebサーバー上に保存されているJSONファイルです:

https://www.example.com/try/angularjs/data/sites.php

{ "sites": [ { "Name": "サンプル", "Url": "www.example.com", "Country": "CN" }, { "Name": "Google", "Url": "www.google.com", "Country": "USA" }, { "Name": "Facebook", "Url": "www.facebook.com", "Country": "USA" }, { "Name": "Weibo", "Url": "www.weibo.com", "Country": "CN" } ] }

AngularJS $http

AngularJS $http は、Webサーバー上のデータを読み取るためのサービスです。

$http.get(url) は、サーバーデータを読み取るための関数です。

非推奨 (v1.5)

v1.5 では$httpのsuccessとerrorメソッドは非推奨です。代わりにthenメソッドを使用してください。

汎用メソッドの例

AngularJS1.5以上 - 例

var app = angular.module('myApp', []); app.controller('siteCtrl', function($scope, $http) { $http({ method: 'GET', url: 'https://www.example.com/try/angularjs/data/sites.php' }).then(function successCallback(response) { $scope.names = response.data.sites; }, function errorCallback(response) { //リクエスト失敗時の実行コード }); });

試してみる »

省略記法の例

AngularJS1.5以上 - 例

<div ng-app="myApp" ng-controller="siteCtrl"> <ul> <li ng-repeat="x in names"> {{ x.Name + ', ' + x.Country }} </li> </ul> </div> <script> var app = angular.module('myApp', []); app.controller('siteCtrl', function($scope, $http) { $http.get("https://www.example.com/try/angularjs/data/sites.php") .then(function (response) {$scope.names = response.data.sites;}); }); </script>

試してみる »

AngularJS1.5以下 - 例

<div ng-app="myApp" ng-controller="siteCtrl"> <ul> <li ng-repeat="x in names"> {{ x.Name + ', ' + x.Country }} </li> </ul> </div> <script> var app = angular.module('myApp', []); app.controller('siteCtrl', function($scope, $http) { $http.get("https://www.example.com/try/angularjs/data/sites.php") .success(function (response) {$scope.names = response.sites;}); }); </script>

試してみる »

アプリケーション解析:

注意:上記のコードの get リクエストは当サイトのサーバーに対するものです。そのままローカルにコピーして実行することはできません。クロスドメイン問題が発生します。解決方法は、Customers_JSON.php のデータを自分のサーバーにコピーすることです。参考:PHP Ajax のクロスドメイン問題の最適な解決策。

AngularJS アプリケーションはng-appで定義されます。アプリケーションは <div> 内で実行されます。

ng-controllerディレクティブはcontroller オブジェクトの名前を設定します。

関数customersControllerは標準のJavaScriptオブジェクトコンストラクタです。。

コントローラーオブジェクトにはプロパティがあります:$scope.names。

$http.get()は、Webサーバーから静的JSONデータを読み取ります。。

サーバーのデータファイルは: https://www.example.com/try/angularjs/data/sites.php。

サーバーからJSONデータを読み込むと、$scope.namesは配列になります。

Note 上記のコードは、データベースデータの読み取りにも使用できます。
その他の拡張