手册
目录
AngularJS $http 服务向服务器发出请求,并返回响应。
向服务器发送一个简单请求,并在标题中显示结果:
运行实例 »Today's welcome message is:
{{myWelcome}}
点击 "运行实例" 按钮查看在线实例
上面的例子使用 $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 是传输数据的绝佳方式,并且很容易在 AngularJS 或任何其他 JavaScript 中使用。
举例:我们在服务器上有一个文件,该文件返回一个包含 15 个客户的 JSON 对象,所有这些都被包装在一个名为 records 的数组中。
请点击此处查看 JSON 对象。
The ng-repeat directive is perfect for looping through an array:
运行实例 »
- {{ x.Name + ', ' + x.Country }}
点击 "运行实例" 按钮查看在线实例
该应用程序定义了 customersCtrl 控制器,具有 scope 和 http 对象。
$http 是一个 XMLHttpRequest 对象,用于请求外部数据。
$http.get() 从 https://www.php.cn/angular/customers.php 读取 JSON 数据。
成功后,控制器在作用域中创建一个属性 myData,其中包含来自服务器的 JSON 数据。
相关
视频
RELATED VIDEOS
科技资讯
1
2
3
4
5
6
7
8
9
精选课程
共5课时
17.2万人学习
共49课时
77万人学习
共29课时
61.7万人学习
共25课时
39.3万人学习
共43课时
71万人学习
共25课时
61.6万人学习
共22课时
23万人学习
共28课时
33.9万人学习
共89课时
125万人学习