AngularJS Http

2022-04-15 14:24 更新

AngularJS XMLHttpRequest

我們可以使用 AngularJS 內(nèi)置的 $http 服務(wù)直接同外部進(jìn)行通信。

$http 服務(wù)只是簡(jiǎn)單的封裝了瀏覽器原生的 XMLHttpRequest 對(duì)象。


$http 是 AngularJS 中的一個(gè)核心服務(wù),用于讀取遠(yuǎn)程服務(wù)器的數(shù)據(jù)。


讀取 JSON 文件

以下是存儲(chǔ)在web服務(wù)器上的 JSON 文件:

Customers_JSON.php

{"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 是一個(gè)用于讀取web服務(wù)器上數(shù)據(jù)的服務(wù)。

$http.get(url) 是用于讀取服務(wù)器數(shù)據(jù)的函數(shù)。

AngularJS 實(shí)例

<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("/statics/demosource/Customers_JSON.php")
    .success(function(response) {$scope.names = response;});
}
</script>

嘗試一下 ?

應(yīng)用解析:

AngularJS 應(yīng)用通過(guò) ng-app 定義。應(yīng)用在 <div> 中執(zhí)行。

ng-controller 指令設(shè)置了 controller 對(duì)象 名。

函數(shù) customersController 是一個(gè)標(biāo)準(zhǔn)的 JavaScript 對(duì)象構(gòu)造器。

控制器對(duì)象有一個(gè)屬性: $scope.names

$http.get() 從web服務(wù)器上讀取靜態(tài) JSON 數(shù)據(jù)。

服務(wù)器數(shù)據(jù)文件為:  /statics/demosource/Customers_JSON.php

當(dāng)從服務(wù)端載入 JSON 數(shù)據(jù)時(shí),$scope.names 變?yōu)橐粋€(gè)數(shù)組。

Note 以上代碼也可以用于讀取數(shù)據(jù)庫(kù)數(shù)據(jù)。
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)