AngularJS學習之旅—AngularJS Http(九)
1、AngularJS XMLHttpRequest
$http 是 AngularJS 中的一個核心服務,用於讀取遠端伺服器的資料。
eg:
// 簡單的 GET 請求,可以改為 POST $http({ method: 'GET', url: '/someUrl' }).then(function successCallback(response) { // 請求成功執行程式碼 }, function errorCallback(response) { // 請求失敗執行程式碼 }); //簡便寫法 $http.get('/someUrl', config).then(successCallback, errorCallback); $http.post('/someUrl', data, config).then(successCallback, errorCallback); eg: var config = { params: { type: "GetPosBrokerDataList" }, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; var data = "Filter=" + escape(angular.toJson($scope.Filter)).replace(/\+/g, '%2b');
此外還有以下簡寫方法:
$http.get
$http.head
$http.post
$http.put
$http.delete
$http.jsonp
$http.patch
2、v1.5 中$http 的 success 和 error 方法已廢棄。使用 then 方法替代。
AngularJS1.5 以上版本 - 例項 eg: $http.get("sites.php") .then(function (response) {$scope.names = response.data.sites;}); AngularJS1.5 以下版本 - 例項 eg: $http.get("sites.php") .success(function (response) {$scope.names = response.sites;});
以下是儲存在web伺服器上的 JSON 檔案:
{ "sites": [ { "Name": "百度", "Url": "www.baidu.com", "Country": "CN" }, { "Name": "Google", "Url": "www.google.com", "Country": "USA" }, { "Name": "Facebook", "Url": "www.facebook.com", "Country": "USA" }, { "Name": "微博", "Url": "www.weibo.com", "Country": "CN" } ] }
AngularJS 1.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("sites.php") .then(function (response) {$scope.names = response.data.sites;}); }); </script>
AngularJS 1.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("sites.php") .success(function (response) {$scope.names = response.sites;}); }); </script>