AngularJS AJAX - $http
- 上一页 AngularJS 服务
- 下一页 AngularJS 表格
$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; }); });
方法
上面的例子使用 $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
The function used to get header information.status
Define the numeric of HTTP status.statusText
Define the string of HTTP status
实例
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; }); });
To handle errors, please send to .then
Add a function to the method:
实例
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
The data obtained from the response should be in JSON format.
JSON is an excellent way to transmit data and is easy to use in AngularJS or any other JavaScript.
For example, we have a file on the server that returns a JSON object containing 15 customers, all wrapped in a name called records
in the array.
Please click here to view the JSON object.
实例
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; }); });
应用程序说明:
该应用程序定义了 customersCtrl
控制器,具有 scope
和 http
对象。
$http
是一个 XMLHttpRequest 对象,用于请求外部数据。
$http.get()
从 https://www.codew3c.com/angular/customers.php 读取 JSON 数据。
成功后,控制器在作用域中创建一个属性 myData
,其中包含来自服务器的 JSON 数据。
- 上一页 AngularJS 服务
- 下一页 AngularJS 表格