AngularJS入门教程之 XMLHttpRequest实例讲解
AngularJSXMLHttpRequest
$http是AngularJS中的一个核心服务,用于读取远程服务器的数据。
读取JSON文件
以下是存储在web服务器上的JSON文件:
http://www.runoob.com/try/angularjs/data/Customers_JSON.php
{
"records":
[
{
"Name":"AlfredsFutterkiste",
"City":"Berlin",
"Country":"Germany"
},
{
"Name":"Berglundssnabbköp",
"City":"Luleå",
"Country":"Sweden"
},
{
"Name":"CentrocomercialMoctezuma",
"City":"MéxicoD.F.",
"Country":"Mexico"
},
{
"Name":"ErnstHandel",
"City":"Graz",
"Country":"Austria"
},
{
"Name":"FISSAFabricaInter.SalchichasS.A.",
"City":"Madrid",
"Country":"Spain"
},
{
"Name":"Galeríadelgastrónomo",
"City":"Barcelona",
"Country":"Spain"
},
{
"Name":"IslandTrading",
"City":"Cowes",
"Country":"UK"
},
{
"Name":"KöniglichEssen",
"City":"Brandenburg",
"Country":"Germany"
},
{
"Name":"LaughingBacchusWineCellars",
"City":"Vancouver",
"Country":"Canada"
},
{
"Name":"MagazziniAlimentariRiuniti",
"City":"Bergamo",
"Country":"Italy"
},
{
"Name":"North/South",
"City":"London",
"Country":"UK"
},
{
"Name":"Parisspécialités",
"City":"Paris",
"Country":"France"
},
{
"Name":"RattlesnakeCanyonGrocery",
"City":"Albuquerque",
"Country":"USA"
},
{
"Name":"Simonsbistro",
"City":"København",
"Country":"Denmark"
},
{
"Name":"TheBigCheese",
"City":"Portland",
"Country":"USA"
},
{
"Name":"Vaffeljernet",
"City":"Århus",
"Country":"Denmark"
},
{
"Name":"WolskiZajazd",
"City":"Warszawa",
"Country":"Poland"
}
]
}
AngularJS$http
AngularJS$http是一个用于读取web服务器上数据的服务。
$http.get(url)是用于读取服务器数据的函数。
AngularJS实例
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8">
<scriptsrc="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<divng-app="myApp"ng-controller="customersCtrl">
<ul>
<ling-repeat="xinnames">
{{x.Name+','+x.Country}}
</li>
</ul>
</div>
<script>
varapp=angular.module('myApp',[]);
app.controller('customersCtrl',function($scope,$http){
$http.get("http://www.runoob.com/try/angularjs/data/Customers_JSON.php")
.success(function(response){$scope.names=response.records;});
});
</script>
</body>
</html>
运行结果:
应用解析:
注意:以上代码的get请求是本站的服务器,你不能直接拷贝到你本地运行,会存在跨域问题,解决办法就是将
Customers_JSON.php的数据拷贝到你自己的服务器上,附:PHPAjax跨域问题最佳解决方案。
AngularJS应用通过ng-app定义。应用在<div>中执行。
ng-controller指令设置了controller对象名。
函数customersController是一个标准的JavaScript对象构造器。
控制器对象有一个属性:$scope.names。
$http.get()从web服务器上读取静态JSON数据。
服务器数据文件为: http://www.runoob.com/try/angularjs/data/Customers_JSON.php。
当从服务端载入JSON数据时,$scope.names变为一个数组。
注意:以上代码也可以用于读取数据库数据。
以上就是对AngularJSXMLHttpRequest资料的整理,后续继续补充,希望能帮助有需要的朋友。