转自:https://www.cnblogs.com/best/tag/Angular/
$http 是 AngularJS 中的一个核心服务,用于读取远程服务器的数据。
使用格式:
// 简单的 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
更详细内容可参见:
读取 JSON 文件
以下是存储在web服务器上的 JSON 文件:
1 { 2 "sites": [ 3 { 4 "Name": "菜鸟教程", 5 "Url": "www.runoob.com", 6 "Country": "CN" 7 }, 8 { 9 "Name": "Google", 10 "Url": "www.google.com", 11 "Country": "USA" 12 }, 13 { 14 "Name": "Facebook", 15 "Url": "www.facebook.com", 16 "Country": "USA" 17 }, 18 { 19 "Name": "微博", 20 "Url": "www.weibo.com", 21 "Country": "CN" 22 } 23 ] 24 }
2.
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <script src="https://cdn.bootcss.com/angular.js/1.6.3/angular.min.js"></script> 6 </head> 7 <body> 8 9 <div ng-app="myApp" ng-controller="siteCtrl"> 10 11 <ul> 12 <li ng-repeat="x in names"> 13 {{ x.Name + ', ' + x.Country }} 14 </li> 15 </ul> 16 17 </div> 18 19 <script> 20 var app = angular.module('myApp', []); 21 22 app.controller('siteCtrl', function($scope, $http) { 23 $http({ 24 method: 'GET', 25 url: 'http://www.runoob.com/try/angularjs/data/sites.php' 26 }).then(function successCallback(response) { 27 $scope.names = response.data.sites; 28 }, function errorCallback(response) { 29 // 请求失败执行代码 30 }); 31 32 }); 33 </script> 34 35 </body> 36 </html>
3.
简写方法实例
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <script src="https://cdn.bootcss.com/angular.js/1.6.3/angular.min.js"></script> 6 </head> 7 <body> 8 9 <div ng-app="myApp" ng-controller="siteCtrl"> 10 11 <ul> 12 <li ng-repeat="x in names"> 13 {{ x.Name + ', ' + x.Country }} 14 </li> 15 </ul> 16 17 </div> 18 19 <script> 20 var app = angular.module('myApp', []); 21 app.controller('siteCtrl', function($scope, $http) { 22 $http.get("http://www.runoob.com/try/angularjs/data/sites.php") 23 .then(function (response) {$scope.names = response.data.sites;}); 24 }); 25 </script> 26 27 </body> 28 </html>
4.
AngularJS1.5 以下版本 - 实例
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> 6 </head> 7 <body> 8 9 <div ng-app="myApp" ng-controller="siteCtrl"> 10 11 <ul> 12 <li ng-repeat="x in names"> 13 {{ x.Name + ', ' + x.Country }} 14 </li> 15 </ul> 16 17 </div> 18 19 <script> 20 var app = angular.module('myApp', []); 21 app.controller('siteCtrl', function($scope, $http) { 22 $http.get("http://www.runoob.com/try/angularjs/data/sites.php") 23 .success(function (response) {$scope.names = response.sites;}); 24 }); 25 </script> 26 27 </body> 28 </html>