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.org.cn/angular/customers.php 读取JSON 数据。
成功时,控制器会在作用域中创建一个名为 myData
的属性,其中包含来自服务器的 JSON 数据。