AngularJS AJAX - $http
$http 是 AngularJS 的一个服务,用于从远程服务器读取数据。
AngularJS $http
AngularJS $http 服务向服务器发出请求,并返回响应。
实例
向服务器发送一个简单请求,并在标题中显示结果:
<div ng-app="myApp" ng-controller="myCtrl">
<p>Today's welcome message is:</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) {
// First function handles success
$scope.content = response.data;
}, function(response) {
// Second function handles error
$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.w3school.com.cn/angular/customers.php 读取 JSON 数据。
成功后,控制器在作用域中创建一个属性 myData,其中包含来自服务器的 JSON 数据。