$http是AngularJS提供的一个服务,用来从远程服务器读取数据。
提供数据
下面的数据由Web服务器提供:
{ "records": [ { "Name" : "Alfreds Futterkiste", "City" : "Berlin", "Country" : "Germany" }, { "Name" : "Berglunds snabbköp", "City" : "Luleå", "Country" : "Sweden" }, { "Name" : "Centro comercial Moctezuma", "City" : "México D.F.", "Country" : "Mexico" }, { "Name" : "Ernst Handel", "City" : "Graz", "Country" : "Austria" }, { "Name" : "FISSA Fabrica Inter. Salchichas S.A.", "City" : "Madrid", "Country" : "Spain" }, { "Name" : "Galería del gastrónomo", "City" : "Barcelona", "Country" : "Spain" }, { "Name" : "Island Trading", "City" : "Cowes", "Country" : "UK" }, { "Name" : "Königlich Essen", "City" : "Brandenburg", "Country" : "Germany" }, { "Name" : "Laughing Bacchus Wine Cellars", "City" : "Vancouver", "Country" : "Canada" }, { "Name" : "Magazzini Alimentari Riuniti", "City" : "Bergamo", "Country" : "Italy" }, { "Name" : "North/South", "City" : "London", "Country" : "UK" }, { "Name" : "Paris spécialités", "City" : "Paris", "Country" : "France" }, { "Name" : "Rattlesnake Canyon Grocery", "City" : "Albuquerque", "Country" : "USA" }, { "Name" : "Simons bistro", "City" : "København", "Country" : "Denmark" }, { "Name" : "The Big Cheese", "City" : "Portland", "Country" : "USA" }, { "Name" : "Vaffeljernet", "City" : "Århus", "Country" : "Denmark" }, { "Name" : "Wolski Zajazd", "City" : "Warszawa", "Country" : "Poland" } ] }
AngularJS $http
AngularJS $http是一个从Web服务器读取数据的核心服务。
$http.get(url)是一个用来从服务器读取数据的函数。
<div ng-app="myApp" ng-controller="customersCtrl"> <ul> <li ng-repeat="x in names"> {{ x.Name + ', ' + x.Country }} </li> </ul> </div> <script> var app = angular.module('myApp', []); app.controller('customersCtrl', function($scope, $http) { $http.get("http://example.php") .success(function(response) {$scope.names = response.records;}); }); </script>
代码解释:
AngularJS application通过ng-app指令定义。application在<div>元素内运行。
ng-controller指令定义了控制器的名称。
customersCtrl函数是一个标准的JavaScript对象构造函数。
AngularJS通过$scope和$http对象调用customersCtrl函数。
$scope是一个appliation object(即application的变量及函数的所有者)。
$http是一个用来请求外部数据的XMLHttpRequest object。
$http.get()函数从服务器读取JSON数据。
如果成功的话,控制器将在$scope对象中创建一个names属性,并将从服务器端返回的JSON数据赋值给这个属性。