# AngularJS XMLHttpRequest
**$http** 是 AngularJS 中的一個核心服務,用于讀取遠程服務器的數據。
## 讀取 JSON 文件
以下是存儲在web服務器上的 JSON 文件:
http://www.w3cschool.cc/try/angularjs/data/Customers_JSON.php
```
[
{
"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) 是用于讀取服務器數據的函數。
## AngularJS 實例
```
<div ng-app="" ng-controller="customersController">
<ul>
? <li ng-repeat="x in names">
??? {{ x.Name + ', ' + x.Country }}
? </li>
</ul>
</div>
<script>
function customersController($scope,$http) {
??? $http.get("http://www.w3cschool.cc/try/angularjs/data/Customers_JSON.php")
??? .success(function(response) {$scope.names = response;});
}
</script>
```
應用解析:
AngularJS 應用通過 **ng-app** 定義。應用在 <div> 中執行。
**ng-controller** 指令設置了 **controller 對象** 名。
函數 **customersController** 是一個標準的 JavaScript **對象構造器**。
控制器對象有一個屬性: **$scope.names**。
**$http.get()** 從web服務器上讀取靜態 **JSON 數據**。
服務器數據文件為:? [**http://www.w3cschool.cc/try/angularjs/data/Customers_JSON.php**](/try/angularjs/data/Customers_JSON.php)。
當從服務端載入 JSON 數據時,**$scope.names** 變為一個數組。
> 
> 以上代碼也可以用于讀取數據庫數據。