Latest web development tutorials

AngularJS Http

$http是AngularJS中的一個核心服務,用於讀取遠程服務器的數據。


讀取JSON 文件

以下是存儲在web服務器上的JSON 文件:

http://www.w3big.com/try/angularjs/data/sites.php

{ " sites " : [ { " Name " : " 本教程 " , " Url " : " www.w3big.com " , " Country " : " CN " } , { " Name " : " Google " , " Url " : " www.google.com " , " Country " : " USA " } , { " Name " : " Facebook " , " Url " : " www.facebook.com " , " Country " : " USA " } , { " Name " : " 微博 " , " Url " : " www.weibo.com " , " Country " : " CN " } ] }


AngularJS $http

AngularJS $http 是一個用於讀取web服務器上數據的服務。

$http.get(url) 是用於讀取服務器數據的函數。

AngularJS 實例

< div ng-app = " myApp " ng-controller = " siteCtrl " > < ul > < li ng-repeat = " x in names " > {{ x.Name + ', ' + x.Country }} </ li > </ ul > </ div > < script > var app = angular.module('myApp', []); app.controller('siteCtrl', function($scope, $http) { $http.get("http://www.w3big.com /try/angularjs/data/sites.php") .success(function (response) {$scope.names = response.sites;}); }); </ script >

嘗試一下»

應用解析:

?注意:以上代碼的get 請求是本站的服務器,你不能直接拷貝到你本地運行,會存在跨域問題,解決辦法就是將Customers_JSON.php 的數據拷貝到你自己的服務器上,附:PHP Ajax跨域問題最佳解決方案。

AngularJS應用通過ng-app定義。 應用在<div> 中執行。

ng-controller指令設置了controller對象名。

函數customersController是一個標準的JavaScript 對象構造器

控制器對像有一個屬性: $scope.names

$http.get()從web服務器上讀取靜態JSON數據

服務器數據文件為: http://www.w3big.com/try/angularjs/data/sites.php

當從服務端載入JSON數據時, $scope.names變為一個數組。

Note 以上代碼也可以用於讀取數據庫數據。