AngularJS XMLHttpRequest
$http是AngularJS 中的一个核心服务,用于读取远程服务器的数据。
以下是存储在web服务器上的 JSON 文件data.json。
[ { "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是一个用于读取web服务器上数据的服务。$http.get(url) 是用于读取服务器数据的函数。
<!DOCTYPE html> <html> <head lang="en"> <meta charset="utf-8"></meta> <title>AngularJS XMLHttpRequest</title> <script src="angular/angular.js"></script> </head> <body> <div ng-app="" ng-controller="customersController"> <ul> <li ng-repeat="x in names">{{ x.Name + ', ' + x.Country }}</li> </ul> </div> </body> <script> function customersController($scope,$http) { $http.get("data.json").success(function(response) {$scope.names = response;}); //$http.get("http://localhost:8088/angularjs-http/data.json").success(function(response) {$scope.names = response;}); } </script> </html>
应用解析:
1.AngularJS 应用通过 ng-app 定义。应用在 <div> 中执行。
2.ng-controller 指令设置了controller 对象名。
3.函数 customersController 是一个标准的 JavaScript 对象构造器。
4.控制器对象有一个属性: $scope.names。
5.$http.get() 从web服务器上读取静态 JSON 数据。
6.当从服务端载入 JSON 数据时,$scope.names 变为一个数组。
运行结果:
工程结构:
相关推荐
QiaoranC 2020-09-25
颤抖吧腿子 2020-09-04
liduote 2020-06-16
阿斌Elements 2020-06-11
xxuncle 2020-06-05
ChinaGuanq 2020-06-05
wanghongsha 2020-03-26
csm0 2020-03-05
shyoushine 2020-02-25
electronvolt 2020-02-12
jsonwoo 2020-01-20
ZadarrienChina 2020-01-07
wwwxuewen 2020-01-04
dynsxyc 2020-01-03
liangjielaoshi 2019-12-27
bowean 2019-12-27
wwwxuewen 2019-12-25
liwusen 2019-12-16
颤抖吧腿子 2019-12-16